JsonNode Null JsonArray Parser - java

I am having a JsonNode response ( unirest ) which I want to parse using JSON Parser.
Now, let's say the structure is somewhat like this :
{
"expand" : "names",
"customfield_1" : null,
"customfield_2" : [ { "email":"123#gmail.com"},{...}]
}
So, the problem is that customfield_1 is a JsonArray and sometimes it can be null.
So, as soon as I use
JSONArray myArr = myObj.getJSONArray("customfield_1")
I get the following error:
org.json.JSONException: JSONObject["customfield_1"] is not a JSONArray.
I tried to change to JsonObject and JsonString but they also didn't help. How to avoid it ?

You can explicitly check if the field is null before getting the array:
JSONArray myArr = myObj.isNull("field") ? null : myObj.getJSONArray("field");
Complete example with your data:
String jsonString = "{\n" +
"\"expand\" : \"names\",\n" +
"\"customfield_1\" : null,\n" +
"\"customfield_2\" : [ { \"email\":\"123#gmail.com\"},{ \"email\":\"abc#gmail.com\"}]\n" +
"}";
JSONObject myObj = new JSONObject(jsonString);
JSONArray myArr1 = myObj.isNull("customfield_1") ? null : myObj.getJSONArray("customfield_1");
JSONArray myArr2 = myObj.isNull("customfield_2") ? null : myObj.getJSONArray("customfield_2");
System.out.println(myArr1);
System.out.println(myArr2);
Output:
null
[{"email":"123#gmail.com"},{"email":"abc#gmail.com"}]

Using object mapper, you can read json and setting deserialization feature FAIL_ON_UNKNOWN_PROPERTIES as false can handle this scenario
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MyObject jsonObj = mapper.readValue(jsonString, MyObject.class);

Related

How to retrieve json array elements from JSON object in Java?

JSONObject firstObject = (JSONObject) jsonParser.parse(new FileReader(firstNamesPath));
I have this JSONObject, and I want to be able to access elements in the array inside of it. The object opens successfully, I just don't know how to access the array called "firstNames". It is in a file, and the object looks like this.
{
"firstNames": [
"Aaron",
"Abigail",
"Albert",
"Bob"
]
}
Edit: I am using org.json.simple.JSONObject . If this is not recommended, I am more than willing to change it.
There are several ways to retrieve the json array value:
Assume we have a jsonString
jsonString = "{\n" + " \"firstNames\": [ \n" + " \"Aaron\",\n" + " \"Abigail\",\n" + " \"Albert\",\n" + " \"Bob\"\n" + " ]\n" + "}";
(since many classes share similar names, I am using the groupId and artifactId for distinction.)
Simple cases: use generic JSONObjects and JSONArrays.
json-simple (which OP is using) json-simple website, maven :
org.json.simple.parser.JSONParser jsonParser = new org.json.simple.parser.JSONParser();
org.json.simple.JSONObject firstObject = (org.json.simple.JSONObject) jsonParser.parse(jsonString);
org.json.simple.JSONArray jsonArray = (org.json.simple.JSONArray) firstObject.get("firstNames");
System.out.println(jsonArray);
JSON in Java (mentioned in adendrata's answer): JSON-Java doc, maven
org.json.JSONObject secondObject = new org.json.JSONObject(jsonString);
org.json.JSONArray jsonArray2 = secondObject.getJSONArray("firstNames");
System.out.println(jsonArray2);
gson: Gson, maven
com.google.gson.JsonObject thirdObject = com.google.gson.JsonParser.parseString(jsonString).getAsJsonObject();
System.out.println(thirdObject.get("firstNames").getAsJsonArray());
For more complicated use cases, if you'd like to define your own class, and want to deserialize JSON string to your class, then you can use Gson or Jackson:
// Create your own class:
/*
public class YourOwnClass {
private List<String> firstNames;
public List<String> getFirstNames() {
return firstNames;
}
}
*/
Gson gson = new Gson();
YourOwnClass customObject1 = gson.fromJson(jsonString, YourOwnClass.class);
System.out.println(customObject1.getFirstNames());
ObjectMapper mapper = new ObjectMapper();
YourOwnClass customObject2 = mapper.readValue(jsonString, YourOwnClass.class);
System.out.println(customObject2.getFirstNames());
you can use JSONArray to get array type of Json and looping to access each index
example:
JSONArray array = firstObject.getJSONArray("firstNames");
for (int i = 0; i < array.length(); i++) {
System.out.println("Hello i'm " + array.get(i));
}
Try to use this : com.alibaba.fastjson.JSONObject, and here's the dependency:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
</dependency>
Then you can directly use the getJSONArray method the answer shown above.

Gson fromJson deserialize

I have the following json:
[
{
"": "",
"substituted_restday": "2020-02-01",
"original_restday": "2020-02-08",
"id": "15d13f70-c0a852c0-3a925f13-6dca1982",
"_UNIQUEKEY_": "15d1592a-c0a852c0-3a925f13b7c65023",
"parentId": ""
},
{
"": "",
"substituted_restday": "2020-02-03",
"original_restday": "2020-02-09",
"id": "15d14d55-c0a852c0-3a925f13-727b70af",
"_UNIQUEKEY_": "15d1592a-c0a852c0-3a925f13-3711a584",
"parentId": ""
}
]
I want to get the value of "substituted_restday" and "original_restday" from the JSON. So I used gson.from with the following syntax to concert it into JAVA object.
String[] str = gson.fromJson(JSON, String[].class);
However, it showed the following error:
com.google.gson.JsonParseException: The JsonDeserializer StringTypeAdapter failed to deserialize json object {"":"","substituted_restday":"2020-02-01","original_restday":"2020-02-08","id":"15d13f70-c0a852c0-3a925f13-6dca1982","_UNIQUEKEY_":"15d1592a-c0a852c0-3a925f13-b7c65023","parentId":""} given the type class java.lang.String
So, how can I get the value of "substituted_restday" and "original_restday" from the JSON? Thank you?
Tree Structure
Gson can parse the JSON into a tree structure, similar to how XML can be parsed into a DOM tree. The nodes of the tree can be one of these subclasses of JsonElement: JsonObject, JsonArray, JsonPrimitive, and JsonNull.
Since the JSON starts with a [, you can parse into a JsonArray, like this:
JsonArray root = gson.fromJson(JSON, JsonArray.class);
for (JsonElement elem : root) {
JsonObject obj = elem.getAsJsonObject();
String substituted_restday = obj.get("substituted_restday").getAsString();
String original_restday = obj.get("original_restday").getAsString();
System.out.printf("substituted_restday = '%s', original_restday = '%s'%n",
substituted_restday, original_restday);
}
List of Maps
Gson can parse the JSON objects into a Map.
List<Map<String, String>> root = gson.fromJson(JSON, new TypeToken<List<Map<String, String>>>() {}.getType());
for (Map<String, String> obj : root) {
String substituted_restday = obj.get("substituted_restday");
String original_restday = obj.get("original_restday");
System.out.printf("substituted_restday = '%s', original_restday = '%s'%n",
substituted_restday, original_restday);
}
Array of POJOs
Gson can parse the JSON objects into POJOs. This is the most type-safe way to handle the data.
MyObj[] root = gson.fromJson(JSON, MyObj[].class);
for (MyObj obj : root) {
System.out.printf("substituted_restday = '%s', original_restday = '%s'%n",
obj.substitutedRestday, obj.originalRestday);
}
class MyObj {
#SerializedName("")
String blank;
#SerializedName("substituted_restday")
String substitutedRestday;
#SerializedName("original_restday")
String originalRestday;
#SerializedName("id")
String id;
#SerializedName("_UNIQUEKEY_")
String uniqueKey;
#SerializedName("parentId")
String parentId;
}
You would likely want getter and setter methods on your POJO. This is just a simplified running example.
Output (from all 3)
substituted_restday = '2020-02-01', original_restday = '2020-02-08'
substituted_restday = '2020-02-03', original_restday = '2020-02-09'
JsonObject jsonObject = gson.fromJson( JSON, JsonObject.class);
then
jsonObject.get(substituted_restday); // returns a JsonElement for that name
jsonObject.get(original_restday);
Imo, you should create a pojo for the json element and then have fromJson method return an array of that pojo's. This link should give you more details - https://howtodoinjava.com/gson/gson-parse-json-array/

Java Rest Template

ResponseEntity<BaseDto> entity = restTemplate.getForEntity("/get/code/IN", BaseDto.class);
System.out.println("entity : " + entity);
System.out.println("entity.getBody() : " + entity.getBody());
System.out.println(entity.getBody().getResponseObject());
As per above rest am getting below format:
{
systemTrack=
{
createUser=admin,
createDate=2016-03-01 18:11:17,
lastUpdatedUser=admin,
lastUpdatedDate=2016-03-01 18:11:17
},
countryCode=IN, countryName=INDIA
}
How to get the values from this format?
Maybe I was unclear with my question, but i got a solution through debug mode.
It was a format which is in Linked hash map ,so what I did was I just wrote below code for json conversion of LinkedHashMap.
LinkedHashMap m = (LinkedHashMap) object;
JSONObject jsonObject = new JSONObject(m);(package of org.json.JSONObject)
and then i assigned to custom class object using
Gson gson = new Gson();
String jsonString = jsonObject.toString();
Object obj = gson.fromJson(jsonString, type);

get elements from json

I want to have a java list for all elements which are in the "in" or "out" element.
My json string:
{"in":[
{"id":4,"ip":"192.168.0.20","pinSysNo":4,"pinSysName":"pg6","folderName":"gpio4_pg6","alias":"d","direction":"digital_in"},
{"id":3,"ip":"192.168.0.20","pinSysNo":3,"pinSysName":"pb18","folderName":"gpio3_pb18","alias":"c","direction":"digital_out"}
],
"out":[
{"id":1,"ip":"192.168.0.20","pinSysNo":1,"pinSysName":"pg3","folderName":"gpio1_pg3","alias":"a","direction":"digital_in"},
{"id":2,"ip":"192.168.0.20","pinSysNo":2,"pinSysName":"pb16","folderName":"gpio2_pb16","alias":"b","direction":"digital_in"}
]
}:""
Until now I did this way:
String message = json.findPath("in").textValue();
But this way can only access to the first hierarchy.
My json example show two elements in the "in" element. How I can get a list of these internal "in" elements?
You could use the library JSONSimple in order to parse your JSON data by this code:
JSONParser parser = new JSONParser();
JSONObject o = (JSONObject) parser.parse(yourJsonAsString);
JSONArray ins = (JSONArray) o.get("in");
JSONArray outs = (JSONArray) o.get("out");
String firstIpAddress = ((JSONObject) ins.get(0)).get("ip").toString();
Thank you for your help. I found an other way to find all sub elements.
Json example:
{"in":[
{"id":4,"ip":"192.168.0.20","pinSysNo":4,"pinSysName":"pg6","folderName":"gpio4_pg6","alias":"d","direction":"digital_in"},
{"id":3,"ip":"192.168.0.20","pinSysNo":3,"pinSysName":"pb18","folderName":"gpio3_pb18","alias":"c","direction":"digital_out"}
],
"out":[
{"id":1,"ip":"192.168.0.20","pinSysNo":1,"pinSysName":"pg3","folderName":"gpio1_pg3","alias":"a","direction":"digital_in"}
,{"id":2,"ip":"192.168.0.20","pinSysNo":2,"pinSysName":"pb16","folderName":"gpio2_pb16","alias":"b","direction":"digital_in"}
]
}
My solution:
JsonNode json = request().body().asJson();
Logger.info("JSON : " + json.findPath("in").findPath("id"));
Logger.info("JSON : " + json.findValues("in"));
List<JsonNode> ins = new org.json.simple.JSONArray();
ins = json.findValues("in");
for (final JsonNode objNode : ins) {
for (final JsonNode element : objNode) {
Logger.info(">>>>>" + element.findPath("id"));
//create my object for database
}
}
Now I can create my Object for the database.
#eztam thank you

Retrieving null and non null string value from JSON String

I have a JSON String that I am parsing, and I want to retrieve the value of the field "pr_num". I am getting this error:
JSONObject["pr_num"] is not a JSONArray.
My code is below:
JSONObject obj = new JSONObject(jsonString);
JSONArray data = obj.getJSONArray("pr_num");
JSONObject obj1= data.getJSONObject(0);
System.out.println("JSON CONTENTS ARE"+obj1.getString("pr_num"));
I want to get values for pr_num field which are 690052 and null.
jsonString is mention below
[{
"executed_by": "vishnuc",
"testplan_id": 17372,
"pr_num": "690052"
},
{
"executed_by": "kkavitha",
"testplan_id": 17372,
"pr_num": null
}]
your jsonString is a json formatted array
So first you have to get it to a json array (not to an json object)
JSONArray obj = new JSONArray(jsonString);
Now you can iterate through the obj array
for(int i=0;i<obj.length();i++){
System.out.println("content one: " + obj.getJSONObject(i).getString("pr_num"));
}
Hope this helps.

Categories