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
}
]
}
Related
In the JSON -photo, I have highlighted the part I need to access in my code and display it in my app.
I tried using JSONArray array = response.getJSONArray("weather[0]"), but that led me literally no where haha
So far i have nothing on the matter. Also here is my code.
public void getWeather(View view) {
String apiKey="40bb658a709ebb7b1c210655e7f5cfe6";
String city=et.getText().toString();
String url="https://api.openweathermap.org/data/2.5/weather?q="+city+"&appid=40bb658a709ebb7b1c210655e7f5cfe6&units=metric";
RequestQueue queue= Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject object = response.getJSONObject("sys");
String country = object.getString("country");
tvcountry.setText(country);
JSONObject object1= response.getJSONObject("main");
String temperature=object1.getString("temp");
tvTemp.setText("Current: " + temperature + " C");
JSONObject object2 = response.getJSONObject("main");
String feelsLike = object2.getString("feels_like");
tvFeels_Like.setText("Feels like: " + feelsLike + " C");
JSONObject object3 = response.getJSONObject("main");
String maxtemp = object3.getString("temp_max");
tvMaxTemp.setText("Max: " + maxtemp + " C");
JSONObject object4 = response.getJSONObject("main");
String mintemp = object4.getString("temp_min");
tvMinTemp.setText("Min: " + mintemp + " C");
JSO
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SecondPage.this, error.toString(), Toast.LENGTH_SHORT).show();
}
});
queue.add(request);
}
Thank you in advance
Use a JSON parser. I am referring to Genson (see http://genson.io/GettingStarted/#deserialize-generic-types):
Genson genson = new Genson();
List<Object> persons = genson.deserialize("[{\"age\":28,\"name\":\"Foo\"}]", List.class);
You can continue with org.json, too:
#Test
void getFirstIndexFromJsonArray() {
// Given
String rawJson = "{\n" +
" \"coors\": {\n" +
" \"long\": -0.7888,\n" +
" \"lat\": 51.9000\n" +
" },\n" +
" \"weather\": [\n" +
" {\n" +
" \"id\": 804,\n" +
" \"main\": \"Clouds\",\n" +
" \"description\": \"overcast clouds\",\n" +
" \"icon\": \"04n\"\n" +
" },\n" +
" {\n" +
" \"id\": 1044,\n" +
" \"main\": \"Thunder\",\n" +
" \"description\": \"Thunderbird\",\n" +
" \"icon\": \"1944x\"\n" +
" }\n" +
" ]\n" +
"}";
// When
JSONObject jsonObject = new JSONObject(rawJson);
JSONArray weather = jsonObject.getJSONArray("weather");
JSONObject firstWeatherEntry = new JSONObject(weather.get(0).toString());
// Then
assertThat(firstWeatherEntry.get("description"), is("overcast clouds"));
}
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've a JSON:
{
"payment_intent": {
"amount": "Amount",
"currency_code": "840",
"invoice_number": "pay-automation-invoice-no-01",
"payment_intent_id": "pay-automation-return-intent-id-01",
"intent_reference_id": "pay-automation-intent-reference-id-01"
},
"payment_refundable_intents": {
"transactions": {
"sales": "pay-automation-sales"
}
}
}
Now, when I tried to replace string "pay-automation-sales" with JSONArray using
payloadJson = payloadJson.replaceAll("pay-automation-sales", salesString);
salesString is
[{"amount":"200.0","payment_intent_id":"29518150","tender_type":"cash","reference_id":"db79893a-9fe0-4391-91f8-fbc-cash-6c88-66db","intent_reference_id":"db79893a-9fe0-4391-91f8-fbc7945ce446","id":"000000893275","status":"Approved"},{"amount":"800.0","payment_intent_id":"29518150","tender_type":"cash","reference_id":"db79893a-9fe0-4391-91f8-fbc-cash-1d12-8466","intent_reference_id":"db79893a-9fe0-4391-91f8-fbc7945ce446","id":"000000893282","status":"Approved"}]
Here, payloadJson is of type String. The replaceAll works fine but actually I want to pass "sales" as an array of object in JSON. But it is getting passed like this and it's not a valid JSON format. Double quotes in value of sales key in JSON causes an issue I think.
"sales": "[{"amount":"200.0","payment_intent_id":"29518150","tender_type":"cash","reference_id":"db79893a-9fe0-4391-91f8-fbc-cash-6c88-66db","intent_reference_id":"db79893a-9fe0-4391-91f8-fbc7945ce446","id":"000000893275","status":"Approved"},{"amount":"800.0","payment_intent_id":"29518150","tender_type":"cash","reference_id":"db79893a-9fe0-4391-91f8-fbc-cash-1d12-8466","intent_reference_id":"db79893a-9fe0-4391-91f8-fbc7945ce446","id":"000000893282","status":"Approved"}]"
How do I replace string in JSON with valid JSON array of objects?
Since you're working with String objects here and not some form of JSON object model, when you did
payloadJson = payloadJson.replaceAll("pay-automation-sales", salesString);
it found the string
pay-automation-sales
within payloadJson and replaced it verbatin with the contents of salesString. Notice that you did NOT tell it to include the quotes in the original string in the part being replaced.
It should be
payloadJson = payloadJson.replaceAll("\"pay-automation-sales\"", salesString);
You would probably be better off using a real JSON library that understands JSON syntax and can manipulate the JSON as an in-memory document model.
Using Java String
public class StringDemo {
static final String originalJson = " {\n"
+ " \"payment_intent\": {\n"
+ " \"amount\": \"Amount\",\n"
+ " \"currency_code\": \"840\",\n"
+ " \"invoice_number\": \"pay-automation-invoice-no-01\",\n"
+ " \"payment_intent_id\": \"pay-automation-return-intent-id-01\",\n"
+ " \"intent_reference_id\": \"pay-automation-intent-reference-id-01\"\n"
+ " },\n"
+ " \"payment_refundable_intents\": {\n"
+ " \"transactions\": {\n"
+ " \"sales\": \"pay-automation-sales\"\n"
+ " }\n"
+ " }\n"
+ "}";
static final String originalArray = "[{\"amount\":\"200.0\",\"payment_intent_id\":\"29518150\",\"tender_type\":\"cash\",\"reference_id\":\"db79893a-9fe0-4391-91f8-fbc-cash-6c88-66db\",\"intent_reference_id\":\"db79893a-9fe0-4391-91f8-fbc7945ce446\",\"id\":\"000000893275\",\"status\":\"Approved\"},{\"amount\":\"800.0\",\"payment_intent_id\":\"29518150\",\"tender_type\":\"cash\",\"reference_id\":\"db79893a-9fe0-4391-91f8-fbc-cash-1d12-8466\",\"intent_reference_id\":\"db79893a-9fe0-4391-91f8-fbc7945ce446\",\"id\":\"000000893282\",\"status\":\"Approved\"}]";
public static void main(String[] args) {
String editedJson = originalJson.replaceAll("\"pay-automation-sales\"", originalArray);
System.out.println(editedJson);;
}
}
Using Jackson
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.*;
public class JacksonDemo {
static final String originalJson = " {\n"
+ " \"payment_intent\": {\n"
+ " \"amount\": \"Amount\",\n"
+ " \"currency_code\": \"840\",\n"
+ " \"invoice_number\": \"pay-automation-invoice-no-01\",\n"
+ " \"payment_intent_id\": \"pay-automation-return-intent-id-01\",\n"
+ " \"intent_reference_id\": \"pay-automation-intent-reference-id-01\"\n"
+ " },\n"
+ " \"payment_refundable_intents\": {\n"
+ " \"transactions\": {\n"
+ " \"sales\": \"pay-automation-sales\"\n"
+ " }\n"
+ " }\n"
+ "}";
static final String originalArray = "[{\"amount\":\"200.0\",\"payment_intent_id\":\"29518150\",\"tender_type\":\"cash\",\"reference_id\":\"db79893a-9fe0-4391-91f8-fbc-cash-6c88-66db\",\"intent_reference_id\":\"db79893a-9fe0-4391-91f8-fbc7945ce446\",\"id\":\"000000893275\",\"status\":\"Approved\"},{\"amount\":\"800.0\",\"payment_intent_id\":\"29518150\",\"tender_type\":\"cash\",\"reference_id\":\"db79893a-9fe0-4391-91f8-fbc-cash-1d12-8466\",\"intent_reference_id\":\"db79893a-9fe0-4391-91f8-fbc7945ce446\",\"id\":\"000000893282\",\"status\":\"Approved\"}]";
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(originalJson);
JsonNode array = mapper.readTree(originalArray);
ObjectNode transactions = (ObjectNode) root.findValue("transactions");
transactions.set("sales", array);
String editedJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root);
System.out.println(editedJson);;
}
}
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");