I'm trying to get the values of Alpha, Beta and Gamma from a nested JSON data file.
I'm trying get the Alpha value using something like this
Object o = new JSONParser().parse(new FileReader(newFile("C:\\Users\\abc\\Documents\\file.json")));
JSONObject jo = (JSONObject) o;
JSONArray resultCode = (JSONArray) jo.get("mkDetails");
JSONObject x = (JSONObject) resultCode.get(0);
x.get("Alpha").toString()
This is the JSON:
{
"metadata": {
"offset": 0,
"psize": 10
},
"svc": [
{
"mNumber": "225",
"markIp": {
"Name": "Ant",
"eDate": "3006-08-01",
"cDate": "9999-12-31"
},
"mkDetails": [
{
"Alpha": "D",
"Beta": "S"
}
],
"mNetDetails": [
{
"Gaama": "213",
"mkTypeCode": "23"
}
]
}
],
"serviceFault": {
"faultType": null,
"faultCode": null,
"message": null
}
}
Here is a possible solution. I'm using Gson lib from google. You can import via maven.
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
Here is the code that parses your JSON.
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public static void parseJson (){
String thisJson ="{\r\n" +
" \"metadata\": {\r\n" +
" \"offset\": 0,\r\n" +
" \"psize\": 10\r\n" +
" },\r\n" +
" \"svc\": [\r\n" +
" {\r\n" +
" \"mNumber\": \"225\",\r\n" +
" \"markIp\": {\r\n" +
" \"Name\": \"Ant\",\r\n" +
" \"eDate\": \"3006-08-01\",\r\n" +
" \"cDate\": \"9999-12-31\"\r\n" +
" },\r\n" +
" \"mkDetails\": [\r\n" +
" {\r\n" +
" \"Alpha\": \"D\",\r\n" +
" \"Beta\": \"S\"\r\n" +
" }\r\n" +
" ],\r\n" +
" \"mNetDetails\": [\r\n" +
" {\r\n" +
" \"Gaama\": \"213\",\r\n" +
" \"mkTypeCode\": \"23\"\r\n" +
" }\r\n" +
" ]\r\n" +
" }\r\n" +
" ],\r\n" +
" \"serviceFault\": {\r\n" +
" \"faultType\": null,\r\n" +
" \"faultCode\": null,\r\n" +
" \"message\": null\r\n" +
" }\r\n" +
"}";
Gson gson = new Gson();
JsonElement jelement = new JsonParser().parse(thisJson);
JsonObject jobject = jelement.getAsJsonObject();
JsonArray jarray = jobject.getAsJsonArray("svc");
jobject = jarray.get(0).getAsJsonObject();
JsonArray netDetailsArr = jobject.getAsJsonArray("mNetDetails");
JsonArray mkDetailsArr = jobject.getAsJsonArray("mkDetails");
jobject = netDetailsArr.get(0).getAsJsonObject();
String gamma = jobject.get("Gaama").getAsString();
System.out.println("gamma==>" + gamma);
jobject = mkDetailsArr.get(0).getAsJsonObject();
String alpha = jobject.get("Alpha").getAsString();
String beta = jobject.get("Beta").getAsString();
System.out.println("alpha ==>" + alpha);
System.out.println("beta ===>"+ beta);
}
console output :
gamma==>213
alpha ==>D
beta ===>S
You can’t just do jo.get("mkDetails"), because jo has no key mkDetails. You have to traverse every level of the tree yourself:
JSONObject root = ...;
JSONArray svc = (JSONArray) root.get("svc");
JSONObject svc0 = (JSONObject) svc.get(0);
JSONObject mkDetails = (JSONObject) svc0.get("mkDetails");
JSONObject mNetDetails = (JSONObject) svc0.get("mNetDetails");
String alpha = (String) mkDetails.get("Alpha");
String beta = (String) mkDetails.get("Beta");
String gamma = (String) mNetDetails.get("Gamma");
Related
I want to get the name of the status from JSON data.
{
"expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
"id": "3876562",
"self": "https://jira2.abc.com/rest/api/2/issue/3876562",
"key": "DEVACDMY-35289",
"fields": {
"status": {
"self": "https://jira2.abc.com/rest/api/2/status/3",
"description": "",
"iconUrl": "https://jira2.abc.com/images/icons/statuses/inprogress.png",
"name": "In Progress",
"id": "3",
"statusCategory": {
"self": "https://jira2.abc.com/rest/api/2/statuscategory/4",
"id": 4,
"key": "indeterminate",
"colorName": "yellow",
"name": "In Progress"
}
}
}
}
I try this but it doesn't work.
Map address = ((Map)jo.get("fields"));
// iterating address Map
Iterator<Map.Entry> itr1 = address.entrySet().iterator();
while (itr1.hasNext()) {
Map.Entry pair = itr1.next();
Map status=((Map)jo.get(pair.key);
Iterator<Map.Entry> itr2 =status.entrySet().iterator(); while(itr2.hasNext())
{
itr1=((Map)itr2.next()).entrySet().iterator();
while(itr1.hasNext())
{
Map.Entry pair=itr1.next();
System.out.println(pair.getKey()+":"+pair.getValue());
}}
Looking at the json, it is not an array, it is simply a JsonObject and to get the string of the status name you need to traverse the same way.
To get the status name there is a hierarchy that you need to follow
JSONObject --> fields*(this is again a JSONObject)* --> status*(this is
again a JSON object)* -> name (this is string)
Look at the following code
String str = "{\n" +
" \"expand\": \"renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations\",\n" +
" \"id\": \"3876562\",\n" +
" \"self\": \"https://jira2.abc.com/rest/api/2/issue/3876562\",\n" +
" \"key\": \"DEVACDMY-35289\",\n" +
" \"fields\": {\n" +
" \"status\": {\n" +
" \"self\": \"https://jira2.abc.com/rest/api/2/status/3\",\n" +
" \"description\": \"\",\n" +
" \"iconUrl\": \"https://jira2.abc.com/images/icons/statuses/inprogress.png\",\n" +
" \"name\": \"In Progress\",\n" +
" \"id\": \"3\",\n" +
" \"statusCategory\": {\n" +
" \"self\": \"https://jira2.abc.com/rest/api/2/statuscategory/4\",\n" +
" \"id\": 4,\n" +
" \"key\": \"indeterminate\",\n" +
" \"colorName\": \"yellow\",\n" +
" \"name\": \"In Progress\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
JSONObject jsonarray = new JSONObject(str);
JSONObject fields = jsonarray.getJSONObject("fields");
JSONObject status = fields.getJSONObject("status");
String name = status.getString("name");
System.out.println("fields : " + fields);
System.out.println("status : " + status);
System.out.println("name: " + name);
output :-
fields : {"status":{"name":"In Progress","self":"https://jira2.abc.com/rest/api/2/status/3","description":"","iconUrl":"https://jira2.abc.com/images/icons/statuses/inprogress.png","id":"3","statusCategory":{"colorName":"yellow","name":"In Progress","self":"https://jira2.abc.com/rest/api/2/statuscategory/4","id":4,"key":"indeterminate"}}}
status : {"name":"In Progress","self":"https://jira2.abc.com/rest/api/2/status/3","description":"","iconUrl":"https://jira2.abc.com/images/icons/statuses/inprogress.png","id":"3","statusCategory":{"colorName":"yellow","name":"In Progress","self":"https://jira2.abc.com/rest/api/2/statuscategory/4","id":4,"key":"indeterminate"}}
name: In Progress
How to iterate json in java. I wanted iterate elements inside payload, grab the first level and second level key and array value. I have converted the same in python. I'm new to java and wanted convert in java. Any help would be appreciated.
Python Code:
import os
import sys
import json
import datetime
def lambda_handler(event, context):
indata = event['payload']
outputDictionary = []
for i in indata:
for j in indata[i]:
for k in indata[i][j]:
outputDictionary.append(dict(source = i,code=j,version=k))
return outputDictionary
Input :
{
"payload": {
"gtl": {
"435185": [
"2019-11-27T14:34:32.368197Z"
]
},
"ptl": {
"A0947863": [
"2019-11-27T14:34:32.368197Z"
]
},
"mtl": {
"A0947863": [
"2019-11-27T14:34:32.368197Z",
"2021-04-27T06:13:12.841968Z"
]
}
}
}
Expected Output
[
{
"source": "gtl",
"code": "435185",
"version": "2019-11-27T14:34:32.368197Z"
},
{
"source": "ptl",
"code": "A0947863",
"version": "2019-11-27T14:34:32.368197Z"
},
{
"source": "mtl",
"code": "A0947863",
"version": "2019-11-27T14:34:32.368197Z"
},
{
"source": "mtl",
"code": "A0947863",
"version": "2021-04-27T06:13:12.841968Z"
}
]
SOLVED IN JAVA:
Java CODE:
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class ParseJson {
public static void main(String[] args) {
String inputJson = "{\r\n" +
" \"payload\": {\r\n" +
" \"gtl\": {\r\n" +
" \"435185\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\"\r\n" +
" ]\r\n" +
" },\r\n" +
" \"ptl\": {\r\n" +
" \"A0947863\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\"\r\n" +
" ]\r\n" +
" },\r\n" +
" \"mtl\": {\r\n" +
" \"A0947863\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\",\r\n" +
" \"2021-04-27T06:13:12.841968Z\"\r\n" +
" ]\r\n" +
" }\r\n" +
" }\r\n" +
"}";
final JSONObject inputJSONOBject = new JSONObject(inputJson);
JSONObject jsonChildObject = (JSONObject)inputJSONOBject.get("payload");
Iterator iterator = jsonChildObject.keys();
while (iterator.hasNext()) {
String key = null;
while(iterator.hasNext()){
String source = (String)iterator.next();
JSONObject codeChildObject = jsonChildObject.getJSONObject(source);
Iterator iterator2 = codeChildObject.keys();
while(iterator2.hasNext()){
String code = (String)iterator2.next();
org.json.JSONArray jsonArray = codeChildObject.getJSONArray(code);
for(int i=0;i<jsonArray.length();i++){
System.out.println("Source:" + source);
System.out.println("CODE:" + code);
System.out.println("Version: "+jsonArray.get(i));
}
}
}
}
}
//System.out.println(inputJSONOBject);
}
You have done everything right except for that extra loop for the first iterator. Following is the complete working solution.
class ParseJson {
public static void main(String[] args) throws Exception {
String inputJson = "{\r\n" +
" \"payload\": {\r\n" +
" \"gtl\": {\r\n" +
" \"435185\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\"\r\n" +
" ]\r\n" +
" },\r\n" +
" \"ptl\": {\r\n" +
" \"A0947863\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\"\r\n" +
" ]\r\n" +
" },\r\n" +
" \"mtl\": {\r\n" +
" \"A0947863\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\",\r\n" +
" \"2021-04-27T06:13:12.841968Z\"\r\n" +
" ]\r\n" +
" }\r\n" +
" }\r\n" +
"}";
JSONArray output = convert(inputJson);
System.out.println(output.toString(5));
}
private static JSONArray convert(String inputJson) throws Exception {
final JSONObject inputJSONOBject = new JSONObject(inputJson);
JSONObject jsonChildObject = (JSONObject) inputJSONOBject.get("payload");
JSONArray outputArray = new JSONArray();
Iterator payloadIterator = jsonChildObject.keys();//gtl,ptl,mtl
while (payloadIterator.hasNext()) {
String source = (String) payloadIterator.next(); //gtl
JSONObject codeChildObject = jsonChildObject.getJSONObject(source);
Iterator codeIterator = codeChildObject.keys();//123, 456
while (codeIterator.hasNext()) {
String code = (String) codeIterator.next();//123
org.json.JSONArray jsonArray = codeChildObject.getJSONArray(code);// t1,t2,t3
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = new JSONObject();
object.put("source", source);
object.put("code", code);
object.put("version", jsonArray.get(i)); //t1
outputArray.put(object);
}
}
}
return outputArray;
}
}
I want to get the number of properties in the rowdata element, in the example JSON below:
"rowData": [
{
"_idName": "CONFIG_DATA_ENTITY_MAP.CONFIG_DT_ENTITY_MAP_ID",
"ERROR": null,
"_id": 1,
"ENTITY_TYPE": "BASE_TIMESERIES",
"DATA_TYPE": "Date",
"FIX_THIS": 0,
"ENTITY_NAME": "ASP",
"SOURCE_TABLE_COLUMN": "AS_OF_DATE"
},
{
"_idName": "CONFIG_DATA_ENTITY_MAP.CONFIG_DT_ENTITY_MAP_ID",
"ERROR": null,
"_id": 2,
"ENTITY_TYPE": "BASE_TIMESERIES",
"DATA_TYPE": "String",
"FIX_THIS": 0,
"ENTITY_NAME": "ASP",
"SOURCE_TABLE_COLUMN": "CUSTOMER_ID"
}
]
Have you tried converting into JSONObject and use jsonObject.length()?
Here's the rough code:
public static void main(String[] args) {
String jsonData = "{\"rowData\": [\n" +
" {\n" +
" \"_idName\": \"CONFIG_DATA_ENTITY_MAP.CONFIG_DT_ENTITY_MAP_ID\",\n" +
" \"ERROR\": null,\n" +
" \"_id\": 1,\n" +
" \"ENTITY_TYPE\": \"BASE_TIMESERIES\",\n" +
" \"DATA_TYPE\": \"Date\",\n" +
" \"FIX_THIS\": 0,\n" +
" \"ENTITY_NAME\": \"ASP\",\n" +
" \"SOURCE_TABLE_COLUMN\": \"AS_OF_DATE\"\n" +
" },\n" +
" {\n" +
" \"_idName\": \"CONFIG_DATA_ENTITY_MAP.CONFIG_DT_ENTITY_MAP_ID\",\n" +
" \"ERROR\": null,\n" +
" \"_id\": 2,\n" +
" \"ENTITY_TYPE\": \"BASE_TIMESERIES\",\n" +
" \"DATA_TYPE\": \"String\",\n" +
" \"FIX_THIS\": 0,\n" +
" \"ENTITY_NAME\": \"ASP\",\n" +
" \"SOURCE_TABLE_COLUMN\": \"CUSTOMER_ID\"\n" +
" }\n" +
"]}";
try {
JSONObject jsonObject = new JSONObject(jsonData.replace("\n", ""));
JSONArray jsonArray = jsonObject.getJSONArray("rowData");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject temp = jsonArray.getJSONObject(i);
System.out.println("temp = " + temp.length());
}
} catch (JSONException err){
Log.d("Error", err.toString());
}
}
Convert you JSON to Object. Pass it to your controller and read the size of it
#RequestBody Map<String, Object> objectMap
objectMap.size()
A raw solution without exception handling. I use the library 'org.json' and had to wrap your raw String inside braces to make it json compatible:
final String jsonString = "{\"rowData\": [\n"
+ " {\n"
+ " \"_idName\": \"CONFIG_DATA_ENTITY_MAP.CONFIG_DT_ENTITY_MAP_ID\",\n"
+ " \"ERROR\": null,\n"
+ " \"_id\": 1,\n"
+ " \"ENTITY_TYPE\": \"BASE_TIMESERIES\",\n"
+ " \"DATA_TYPE\": \"Date\",\n"
+ " \"FIX_THIS\": 0,\n"
+ " \"ENTITY_NAME\": \"ASP\",\n"
+ " \"SOURCE_TABLE_COLUMN\": \"AS_OF_DATE\"\n"
+ " },\n"
+ " {\n"
+ " \"_idName\": \"CONFIG_DATA_ENTITY_MAP.CONFIG_DT_ENTITY_MAP_ID\",\n"
+ " \"ERROR\": null,\n"
+ " \"_id\": 2,\n"
+ " \"ENTITY_TYPE\": \"BASE_TIMESERIES\",\n"
+ " \"DATA_TYPE\": \"String\",\n"
+ " \"FIX_THIS\": 0,\n"
+ " \"ENTITY_NAME\": \"ASP\",\n"
+ " \"SOURCE_TABLE_COLUMN\": \"CUSTOMER_ID\"\n"
+ " }\n"
+ "]}";
public int numberOfChildElement(String data, int elementIndex){
JSONObject jsonObject = new JSONObject(data);
JSONArray jsonArray = jsonObject.getJSONArray("rowData");
return jsonArray.getJSONObject(elementIndex).length();
}
So if you call the method 'numberOfChildElement' passing in the raw String and the index of the element you want to get the count of (0 or 1 in your example), you should get the result you want.
package com.example.demo;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ColumnDefValidator {
public static void columnDef(JSONObject jsonObjects) {
int templengthColumn = 0;
int templelenghtRow = 0;
try {
JSONArray columnDefsData = jsonObjects.getJSONArray("columnDefs");
JSONArray rowDataDefs = jsonObjects.getJSONArray("rowData");
for (int i = 0; i < columnDefsData.length(); i++) {
JSONObject temp = columnDefsData.getJSONObject(i);
templengthColumn = temp.length();
}
for (int i = 0; i < rowDataDefs.length(); i++) {
JSONObject temp = rowDataDefs.getJSONObject(i);
templelenghtRow = temp.length();
}
System.out.println(templengthColumn);
System.out.println(templelenghtRow);
} catch (JSONException err) {
System.out.println(err.toString());
}
}
public static JSONObject parseJSONFile(String filename) throws JSONException, IOException {
String content = new String(Files.readAllBytes(Paths.get(filename)));
return new JSONObject(content);
}
public static void main(String[] args) throws IOException, JSONException, ParseException {
String filename = "/home/niteshb/WaveProject/working_dir/jsonoutput/aggrid/resp_attribute_report.json";
JSONObject jsonObject = parseJSONFile(filename);
columnDef(jsonObject);
}
}
I am trying to loop through the json file and find the value of particular json object.
Here is my sample json:
{
"diagram":[
{"size":{"width":30,"height":20},"color":"blue","id":1},
{"color":"red","id":2},
{"size:{"height":30}", "id":3}
]
}
What i want to do is to iterate through the file and find the "id" element.
I used below code to convert the JsonFile into JsonObject and to get the value of "diagram" object
JSONArray jsonArray = new JSONArray();
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("D:/test.json"));
JSONObject jsonObj = (JSONObject) obj;
for(Iterator iterator = jsonObj.keySet().iterator(); iterator.hasNext();) {
String diagramKey = (String) iterator.next();
jsonArray.put(jsonObj.get(diagramKey));
}
With the above code i was able to get the value of diagram object and i have put that into the jsonArray
When i am trying to print the array object i am getting output as
[[
{"size":{"width":30,"height":20},"color":"blue","id":1},
{"color":"red","id":2},
{"size:{"height":30}", "id":3}
]]
and the jsonArray length is coming as 1.
How to loop through the above jsonArray and find the id of each individual element
Verify your JSON too and check below code.
public class MyTest {
public static void main(String[] args) throws JSONException {
String str = "{\r\n" +
" \"diagram\": [{\r\n" +
" \"size\": {\r\n" +
" \"width\": 30,\r\n" +
" \"height\": 20\r\n" +
" },\r\n" +
" \"color\": \"blue\",\r\n" +
" \"id\": 1\r\n" +
" },\r\n" +
" {\r\n" +
" \"color\": \"red\",\r\n" +
" \"id\": 2\r\n" +
" },\r\n" +
" {\r\n" +
" \"size\": {\r\n" +
" \"height\": 30\r\n" +
" },\r\n" +
" \"id\": 3\r\n" +
" }\r\n" +
" ]\r\n" +
"}";
JSONObject jo = new JSONObject(str);
final JSONArray geodata = jo.getJSONArray("diagram");
int arrLength = geodata.length();
for(int i = 0; i< arrLength;i++) {
jo = geodata.getJSONObject(i);
System.out.println(jo.get("id"));
}
}
}
Your json format is wrong.
You can always validate your json format using tools online
https://jsonformatter.curiousconcept.com/
https://jsonformatter.org/
Correct json format
{
"diagram":[
{
"size":{
"width":30,
"height":20
},
"color":"blue",
"id":1
},
{
"color":"red",
"id":2
},
{
"size":{
"height":30
},
"id":3
}
]
}
I have a code where i get a Json response in array format
{ "data": {
"findAllUsers": {
"pendingUsers": [
{
"userId": "123",
"firstName": "FirstNamemz8",
"lastName": "LastName0Hz",
"status": "Pending"
},
{
"userId": "456",
"firstName": "FirstNameEgl",
"lastName": "LastNameVCC",
"status": "Pending"
}
]
} }}
I need to get the list of userID in list format. below is the code i used which doesnt works. Kindly help me out in this with working code.
package com.deedsing;
import com.deedsing.bean.SnowIncident;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Test {
public static void main(String[] args) {
String jString="{ \"data\": {\r\n" +
"\"findAllUsers\": {\r\n" +
" \"pendingUsers\": [\r\n" +
" {\r\n" +
" \"userId\": \"123\",\r\n" +
" \"firstName\": \"FirstNamemz8\",\r\n" +
" \"lastName\": \"LastName0Hz\",\r\n" +
" \"status\": \"Pending\"\r\n" +
" },\r\n" +
" {\r\n" +
" \"userId\": \"456\",\r\n" +
" \"firstName\": \"FirstNameEgl\",\r\n" +
" \"lastName\": \"LastNameVCC\",\r\n" +
" \"status\": \"Pending\"\r\n" +
" }\r\n" +
" ]\r\n" +
"} }}";
Gson json = new GsonBuilder().create();
JsonElement elem = new JsonParser().parse(jString);
JsonObject obj = elem.getAsJsonObject();
JsonArray jarray = obj.get("data").getAsJsonObject().get("findAllUsers").getAsJsonObject().get("pendingUsers").getAsJsonArray();
for(int i = 0; i < jarray.size(); i++)
{
JsonElement elem2 = jarray.get(i);
JsonObject obj2 = elem2.getAsJsonObject();
System.out.println("UserID -->" + obj2.get("userId").getAsString());
}
}
}