JSON serialize gives null in the java POJO - java

I have a java POJO with values set. i set values like the following :
CreateRequisitionRO[] request = new CreateRequisitionRO[1];
request[0].setPortfolio("HEXGENFUND");
request[0].setTransSrlNo(new BigDecimal(1));
request[0].setTransCode("BUY");
request[0].setInvestReason("009");
request[0].setInflowOutflow(InflowOutflow.I);
request[0].setTradeDate(new LocalDate());
request[0].setTradeDate(new LocalDate());
and this is my json serialize method :
public String serialiseRequisionRO(CreateRequisitionRO[] requestObj) {
//CreateRequisitionRO requestObj = new CreateRequisitionRO();
JSONSerializer serializer = new JSONSerializer();
System.out.println("JSON : "+serializer.serialize(requestObj));
return serializer.serialize(requestObj);
}
but when i excute the program i get Null Pointer exception at this line request[0].setPortfolio("HEXGENFUND");
how to resolve it. and what could be the solution.
Please help me to resolve this.
Best Regards
Anto

You need to initialize array element/s.
request[0] = new CreateRequisitionRO();

Related

Class cast Exception during JSON Parsing

I have been trying to parse this string to get the value of the Target-key
{
"Type" : "Notification",
"MessageId" : "something",
"Message" : "{\"buildId\":\"something\",\"somekey\":\"somevalue\",\"startTimeMillis\":1592526605121,\"table\":{\"key1\":\"val1\",\"tableName\":\"some table\",\"tableprop\":{\"bucketCount\":123,\"bucketColumns\":[\"X\",\"Y\"]},\"tableSortProperty\":{\"sortColumns\":[\"X\",\"Y\"]}},\"createStatementLocation\":{\"s3Bucket\":\"somebucket\",\"s3Prefix\":\"someprefix\"},\"Target-key\":\"Target-Value\"}",
"Timestamp" : "2020-06-19T19:23:46.378Z"
}
I have tried the following approach:
message.getBody() returns the Json String. Here message is the SQS Message object
Approach 1:
JSONObject jsonObject = new JSONObject(message.getBody());
JSONObject obj = (JSONObject) jsonObject.get("Message");
String res = (String)obj.get("Target-key");
I am getting the error at line 2 of above code
java.lang.String cannot be cast to org.json.JSONObject: java.lang.ClassCastException
java.lang.ClassCastException: java.lang.String cannot be cast to org.json.JSONObject
Approach 2:
Using Jackson also produces class cast exception on line2 again.
Map<String,Map<String,String> > mymap;
mymap = objectMapper.readValue(message.getBody(), Map.class);
Map<String, String> mymap2 = mymap.get("Message");
String res = mymap2.get("Target-key");
Approach 3:
Also Tried using Jackson Tree Node
However, the below solution do seem to work but I want to know why the above approach is failing
Map<String,String> messageMap;
messageMap = objectMapper.readValue(message.getBody(), Map.class);
Map<String,String> mmap = objectMapper.readValue(messageMap.get("Message"), Map.class);
String res = mmap.get("Target-key");
PS:I have tried many alternatives and similar question on stack overflow but it is not helping my case.
The actual key and value have been replaced with some-key and some-value.
EDIT:
I sneaked into the source data and updated JSON
Now that we can see the original source your problem is obvious. The value of Message is a string instead of a nested object.
JSONObject jsonObject = new JSONObject(message.getBody());
JSONObject obj= new JSONObject(jsonObject.getString("Message"));
There is a parsing error in your json at
"bucketCount": XYZ,
XYZ myst be inside inverted commas like "XYZ".
You can check your json at http://json2table.com
It fails because the result of parsing is not a String, nor Map<String,String> and not even a Map<String,Map<String,String>>. The result object has more complex structure.
If you need to have the object in yuor app for further use, you can create a class(es) to store and Jackson will deserialize it into object.
In case you don't need the whole object, there is readTree method on Jackson library.
It will create JsonNode object you can navigate with your tag names. Something like
res.get("Message").get("Target-key")
(consider properly formed input JSON)

JSON Parsing instance type with Array or String [duplicate]

This question already has answers here:
Make Jackson interpret single JSON object as array with one element
(3 answers)
Closed 4 years ago.
I am trying to parse JSON data using Jackson, found that instance some time as array or String
JSON DATA instance with String :
{
"Value" : "1"
}
JSON DATA instatnce with Array :
{
"Value" : ["ram","kumar"]
}
due to this getting error are given below
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
deserialize instance of `java.util.ArrayList` out of VALUE_STRING token
In this case how to solve this,thankyou
current java code
ObjectMapper objectMapper = new ObjectMapper();
try {
String jsonInString = objectMapper.writeValueAsString(products.get(j));
InventoryParser inventoryParser =
objectMapper.readValue(jsonInString, InventoryParser.class);
System.out.println(inventoryParser.getName());
}
catch (IOException e)
{
e.printStackTrace();
}
}
Read into a map data structure like so and then process it.
final Map<String, Object> result = new ObjectMapper().readValue(jsonStr,
new TypeReference<Map<String, Object>>() {
});
You can write a custom deserializer and write custom logic to handle such data. In the deserializer you can check whether the node is an array or not.
Please refer deserialize xml to pojo using jackson xml mapper (The example is in XML but can be similarly used for JSON too by using ObjectMapper)

parsing json & mapping xml with java com.fasterxml.jackson.databind.JsonNode;

New to java here coming from .NET and having some issue with parsing json. I need to be able to verify that a node exists and that the value is also not null before attempting to try and retrieve the value. I tried the following but not sure if this is the best approach.
ObjectMapper mapper = new ObjectMapper();
JsonNode messageNode = mapper.readTree(post);
id = messageNode.path("id").asText();
author = messageNode.path("actor").get("displayName").asText();
authorId = messageNode.path("actor").get("id").asText();
authorLink = messageNode.path("actor").get("link").asText();
if (! messageNode.path("actor").get("link").isMissingNode()) {
imageLink = messageNode.path("actor").get("link").asText();
}
pauthor = messageNode.path("actor").get("preferredUsername").asText();
Do I just use this for each field but how do I also check for null value?
Sounds like you should benefit from using JsonNode.has(...) and JsonNode.hasNotNull(...) methods.

Parsing JSON server response into JSON Array

I am using Java to parse a JSON response from a server. My end goal is to have the data from results in an Array. Currently I am using this to try and get the results:
JSONArray jArray = myResponse.getJSONArray("results");
This code fails because it is looking for an array of objects, rather than an array of strings:
org.json.JSONException: Value blah at 0 of type java.lang.String cannot be converted to JSONObject
This is my server's JSON Response:
{
status: "OK",
results: [
"blah",
"bleh",
"blah"
]
}
Is there a simple way to get the "results" value into an array? Or should I just write my own parser.
Thanks
---------- UPDATE ----------
Looks like my problem was actually occuring somewhere else, and not where the JSON attribute "results" was being converted into a JSONArray.
Sorry and thanks for the answers, they helped me realize I was looking in the wrong spot.
This should be it. So you're probably trying to get JSONObject instead of String inside the results aarray.
JSONObject responseObject = new JSONObject(responseString);
JSONArray resultsArray = responseObject.getJSONArray("results");
for (int i=0; i<resultsArray.length(); i++)
String resultString = resultsArray.getString(i);
As you will probably have more properties, than only the String[] result, I recommend to define a DTO like this:
public class Dto {
//of course you should have private fields and public setters/getters, but this is only a sample
public String status;
public List<String> results;//this can be also an array
}
And then in your code:
ObjectMapper mapper = new ObjectMapper();
Dto dto = mapper.readValue(inputDtoJson, Dto.class);//now in dto you have all the properties you need

Possibility of using Generic function to convert any Java Object to JSON

I would like to know if it is possible to convert any Java object to JSON object. Currently I have the following code.
JSONArray data = new JSONArray();
for (User user : users) {
JSONArray row = new JSONArray();
row.put(user.getId()).put(user.getUserName()).put(user.isEnabled());
data.put(row);
}
The current issue is different object (e.g. User and Admin) will have different property, thus the above code will work for other object. I am thinking of putting a similar code in my GenericHibernateDAO in order to automatically convert any list into a json list.
You can serialize your java object to json object. There are n number of library is available ex gson, jettyson, flexjson etc.
GSON example -
Gson gson = new Gson();
Collection<Integer> ints = Lists.immutableList(1,2,3,4,5);
(Serialization)
String json = gson.toJson(ints); ==> json is [1,2,3,4,5]
Here i exemplify the way of converting POJO to json using jackson
create your pojo : User user = new User();
you can set or get values to/from user
create ObjectMapper : ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(user);// object to json

Categories

Resources