How to check if JSON is nested or not in Java? - java

I have this JSON:
{
"id": 2643743,
"dt": 1485789600,
"clouds": {
"all": 90
}
}
In this JSON, how can I check for a key that has a nested JSON? For example, how can I check if clouds have nested JSON?
JSONObject json = readJsonFromUrl("http://samples.openweathermap.org/data/2.5/weather?q=London,uk&APPID=916c290adb437e1cc53eab01798225ed");
Iterator keys = json.keys();
Iterator inskeys = json.keys();
String keyStr = null;
while(keys.hasNext()) {
keyStr = (String) keys.next();
Object keyvalue = json.get(keyStr);
Object keyType = keyvalue.getClass().getSimpleName();
...

Here is simple example:
String JSON = "{\"id\":2643743,\"dt\":1485789600,\"clouds\":{\"all\":90}}";
JSONObject jsonObject = new JSONObject(JSON);
JSONObject getSth = jsonObject.getJSONObject("clouds");

Related

How to get key value of objects inside an array in Java

I am trying to get key and value of json array response. I want to map each key and get its value. Currently I am looping the result of my response.
public void getResult(Object result) {
ObjectMapper mapper = new ObjectMapper();
Object map = null;
try {
map = mapper.readValue((String) result, Object.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
JSONArray jsonArray = (JSONArray) map;
for (Object o : jsonArray) {
JSONObject json = new JSONObject((Map) o);
for (Object obj : json.entrySet()) {
Map.Entry entry = (Map.Entry) obj;
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
}
Here is the list of objects inside an array
[
{
"uniqueName": "INVinv0001-5179",
"documentType": "Invoice",
"description": "INVinv0001-5179",
"assignedDate": "2020-10-22",
"approver": "10011618",
"email": "adrian.cabral#example.com",
"fullURL": "http://localhost:8080/webjumper?itemID=AEz0AQNDZtZ%21ca3&awcharset=UTF-8",
"attachments": [
"AEz0ACMDZtZ!cnN"
]
},
{
"uniqueName": "INVinv0001-5179",
"documentType": "Invoice",
"description": "INVinv0001-5179",
"assignedDate": "2020-10-22",
"approver": "10003025",
"email": "dummy#example.com",
"fullURL": "http://localhost:8080/webjumper?itemID=AEz0AQNDZtZ%21ca3&awcharset=UTF-8",
"attachments": [
"AEz0ACMDZtZ!cnN"
]
}
]
I keep getting this error.
java.lang.ClassCastException: class java.util.ArrayList cannot be cast to class org.json.simple.JSONObject
Try to convert map object to JSONArray rather than JSON Object. It would give you JSONObject to work with directly.
public void getResult(Object result) {
ObjectMapper mapper = new ObjectMapper();
Object map = null;
try {
map = mapper.readValue((String) result, Object.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
JSONArray json = (JSONArray) map;
for (int i=0; i < json.length(); i++) {
JSONObject e = json.get(i);
System.out.println(e);
}
}
You are casting it wrong.
JSONObject json = (JSONObject) map;
This casting is wrong (JSONObject) map. it should be (JSONArray) map.
Next time before casing object, you perhaps want to check type of object like this.
System.out.println(map.getClass().getName());

How to read a nested, non-array JSON in java?

I've a JSON file with:
"items": [
{
(...)
"volumeInfo": {
(...)
"readingModes": {
"text": true,
"image": true
},
(...)
}
How do I access 'image' and 'text' in "readingModes"? I've tried both
JSONArray readingModes = volumeInfo.optJSONArray("readingModes");
which worked for data with squared bracket, but in this case returns nulls
and
JSONObject readingModes = gobj.getJSONObject("readingModes");
which returns error - JSONObject["readingModes"] not found, where gobj is accessed:
JSONObject jobj = new JSONObject(jsonData);
JSONArray items = jobj.getJSONArray("items");
Iterator i = items.iterator();
while(i.hasNext())
{
JSONObject gobj = (JSONObject) i.next();
(...)
}
JSONObject jobj = new JSONObject(jsonData);
JSONArray items = jobj.getJSONArray("items");
Iterator i = items.iterator();
while(i.hasNext())
{
JSONObject gobj = (JSONObject) i.next();
JSONObject volumeInfo = gobj.getJSONObject('volumeInfo');
JSONObject readingModes = volumeInfo.getJSONObject('readingModes');
(...)
}
According to your JSON you need to do this.
Since readingModes is in volumeInfo, you first need to get JSON object of volumeInfo in order to access readingModes.

How to extract specific fields of JSON Array in Java and store it in String

I have JSON data and want to extract data of only specific fields in Java and store it in String.
Example,
From issues, key:651, From project name:test, updated, created This details for all records of array issues.
Sample JSON Data:
"issues": [
{
"expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields",
"key": "651",
"fields": {
"project": {
"name": "test",
"Urls": {
"48x48": "https://test1.com",
"24x24": "https://test2.com"
},
},
"updated": "2019-03-05T13:24:56.000-0800",
"created": "2019-03-05T13:24:56.000-0800",
"status": {
"description" : "";
"name": "",
}
}
},
{
"expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields",
"key": "321",
"fields": {
"project": {
"name": "test2",
"Urls": {
"48x48": "https://test1.com",
"24x24": "https://test2.com"
},
},
"updated": "2019-03-05T13:24:56.000-0800",
"created": "2019-03-05T13:24:56.000-0800",
"status": {
"description" : "";
"name": "",
}
}
}
]
Java code that I have tried so far jar used - (gson-2.8.5)
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues = (JsonArray) object.get("issues");
JsonObject issues0 = (JsonObject) issues.get(0);
JsonObject issues0data = (JsonObject) issues0.get("key");
String issue_key = issues0data.get("issue_key").getAsString();
System.out.println("Value of key is -> " + issue_key); // java.lang.ClassCastException: com.google.gson.JsonPrimitive cannot be cast to com.google.gson.JsonObject
Updated Code
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues_data = (JsonArray) object.get("issues");
for(int i=0; i<issues_data.size(); i++)
{
JsonObject issues = (JsonObject) issues_data.get(i);
String issues_key = (String) issues.get("key").toString();
String project_name = (String) issues.get("name").toString(); // returns null
}
You can convert to string when you get the value.
Change your code like this see if it helps.
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues = (JsonArray) object.get("issues");
JsonObject issues0 = (JsonObject) issues.get(0);
String issue_key = (String) issues0.get("key");//<---here
System.out.println("Value of key is -> " + issue_key);
Update
If you want all values just put it inside "for":
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues = (JsonArray) object.get("issues");
for(int i=0; i<issues.size(); i++){
JsonObject issue = (JsonObject) issues.get(i);
String issue_key = (String) issue.get("key");
System.out.println("Value of key" + Integer.toString(i + 1) + " is -> " + issue_key);
}
Update 2
The data "updated" and "created" are not inside "issues" they are inside "fields" to get access to them you need to get them from "fields". You have to go inside level by level to get access to variables:
JsonObject object = (JsonObject) new JsonParser().parse(new FileReader("C:\\MyData\\response.json"));
JsonArray issues = (JsonArray) object.get("issues");
for(int i=0; i<issues.size(); i++){
JsonObject issue = (JsonObject) issues.get(i);
String issue_key = (String) issue.get("key");
JsonObject fields = (JsonObject) issues.get("fields");
JsonObject project = (JsonObject) issues.get("project");
String project_name = (String) project.get("key");
String fields_updated = (String) fields.get("updated");
String fields_created = (String) fields.get("created");
System.out.println("Value of key" + Integer.toString(i + 1) + " is -> " + issue_key);
}
You are getting an error because you are casting a JsonPrimitive to JsonObject. So instead of using
JsonObject issues0data = (JsonObject) issues0.get("key");
you should do
String issues0data = issues0.get("key").getAsString();
System.out.println("Value of key is -> " + issues0data);
Here, calling getAsString() will invoke JsonPrimitive.getAsString() method. This will take care if the primitive is boolean/number/string and convert it to string.

How to customize a json that is created using Gson object in java

I have this JSON object that I've created using GSON:
{
"data": {
"isDeleted": false,
"period": 201601,
"columnMap": {
"1c49eb80-7b53-11e6-bc4b-afbeabb62718": "5000",
"1c49eb80-7b52-11e6-bc4b-afbeabb62718": "hello",
"03a534c0-a7f1-11e6-9cde-493bf5c47f4": "AUS",
"03a534c0-a7fa-11e6-9cde-493bf5c47f4": "123"
}
}
}
But my requirement is for it to look like
{
"data": {
"isDeleted": false,
"period": 201601,
"1c49eb80-7b53-11e6-bc4b-afbeabb62718": "5000",
"1c49eb80-7b52-11e6-bc4b-afbeabb62718": "hello",
"03a534c0-a7f1-11e6-9cde-493bf5c47f4": "AUS",
"03a534c0-a7fa-11e6-9cde-493bf5c47f4": "123"
}
}
}
How do I solve this, because all the values in "columnMap" are generated dynamically.
You need to create instance updateJsonObj of JsonObject to update key and value of columnMap using for each loop. Following code snippet is the solution :
String json = "{ \"data\": {\"isDeleted\": false,\"period\": 201601,"
+ "\"columnMap\": {\"1c49eb80-7b53-11e6-bc4b-afbeabb62718\": \"5000\","
+ "\"1c49eb80-7b52-11e6-bc4b-afbeabb62718\": \"hello\","
+ "\"03a534c0-a7f1-11e6-9cde-493bf5c47f4\": \"AUS\", "
+ "\"03a534c0-a7fa-11e6-9cde-493bf5c47f4\": \"123\"}}}";
Gson gson = new Gson();
JsonObject root = new JsonParser().parse(json).getAsJsonObject();
JsonElement dataElement = root.get("data");
// cobj has value of colummMap of json data
JsonObject cobj = (JsonObject) root.get("data").getAsJsonObject().get("columnMap");
JsonObject updateJsonObj = root;
// remove columnMap node as you wanted !
updateJsonObj.get("data").getAsJsonObject().remove("columnMap");
for (Entry<String, JsonElement> e : cobj.entrySet()) {
//update updateJsonObj root node with key and value of columnMap
updateJsonObj.get("data").getAsJsonObject().addProperty(e.getKey(), e.getValue().getAsString());
}
String updateJson = gson.toJson(updateJsonObj);
System.out.println(updateJson);

parse Json array error "jsonObject cannot be resolved"

I have the following Json and I want to parse the array (cars) ,
[
{
"name": "John",
"city": "Berlin",
"cars": [
"audi",
"bmw"
],
when i tried with the following code i got error
JSONParser parser = new JSONParser();
JSONArray a = (JSONArray) parser.parse(new FileReader(
"C:\\General\\Json\\json.txt"));
for (Object o : a) {
JSONObject person = (JSONObject) o;
String name = (String) person.get("name");
System.out.println(name);
String city = (String) person.get("city");
System.out.println(city);
String job = (String) person.get("job");
System.out.println(job);
}
here is the error "jsonObject cannot be resolved"
how should i overcome it?
JSONArray cars = (JSONArray) jsonObject.get("cars");
you did not declared jsonObject
JSONArray cars = (JSONArray) person.get("cars"); try this instead of JSONArray cars = (JSONArray) jsonObject.get("cars"); this PSR also correct

Categories

Resources