Parse a complex JSON result - java

I have a json (result) like the below , i need the value of Key "extra", that is "contact office".
I tried the below code, but it did not work, can you help?
JSONArray jsonArray = new JSONArray(result.toString().trim());
JSONObject json = jsonArray.getJSONObject(0).getJSONObject("student").getJSONArray("department").getJSONObject(0).getJSONObject("classes");
String val=json.getString("extra");
// JSON Example
{
"student": [
{
"department" : [
{
"classes" : [
{
"grade" : "A",
"fine" : "No"
},
{
"grade" : "B",
"fine" : "Yes",
"extra" : "contact office"
},
{
"grade" : "C",
"fine" : "NA"
}
],
}
],
}
],
}

You mixed up JSONArray and JSONObject a few times, not sure exactly what I had to change but the following will work:
JSONObject jsonObject = new JSONObject(result.toString().trim());
JSONArray jsonArray = jsonObject
.getJSONArray("student").getJSONObject(0).getJSONArray("department").getJSONObject(0)
.getJSONArray("classes");
String val = jsonArray.getJSONObject(1).getString("extra");

Is this a full sample? If so it doesn't start out as an array. Student is and object not an array. If it is just a sample of one item in the array then you're okay.
The second thing I noticed is: getJSONObject("classes"). Classes is an array not an object, this won't work.

Would you like to consider using JsonPath. You could do something like this -
String[] extraValues = JsonPath.read(json, "$.student[0].department[0].classes[*].extra");

Related

Parsing through JSON and selecting multiple items in java

I currently have this JSON:
[
{
"example": "12345678",
"test": "0",
"name": "tom",
"testdata": "",
"testtime": 1531209885613
},
{
"example": "12634346",
"test": "43223452234",
"name": "jerry",
"testdata": "pawenkls",
"testtime": 1531209888196
}
]
I am trying to parse through the array to find a value of "testdata" that matches the value of "testdata" that I have generated, which I am currently doing like so:
JsonArray entries = (JsonArray) new JsonParser().parse(blockchainJson);
JsonElement dataHash = ((JsonObject)entries.get(i)).get("dataHash");
Then I wish to find the value of "example" that is in the same array as the "testdata" with the value "pawenkls".
How do I search for the "example" value that is in the same group as the value of "test data" that I have found?
You need to run through the objects in the array and check the value of the testData field against yours. Then read its example field.
String testData = "pawenkls";
JsonArray entries = (JsonArray) new JsonParser().parse(blockchainJson);
String example = null;
for(JsonElement dataHashElement : entries) {
JsonObject currentObject = dataHashElement.getAsJsonObject();
if(testData.equals(currentObject.get("testdata").getAsString())) {
example = currentObject.get("example").getAsString();
break;
}
}
System.out.println("example: "+example);
This prints out
example: 12634346
Here is a Java 8 version doing the same thing:
String testData = "pawenkls";
JsonObject[] objects = new Gson().fromJson(blockchainJson, JsonObject[].class);
Optional<JsonObject> object = Arrays.stream(objects)
.filter(o -> testData.equals(o.get("testdata").getAsString()))
.findFirst();
String example = null;
if(object.isPresent())
example = object.get().get("example").getAsString();
System.out.println("example: "+example);

Accessing elements in JSON array

I haven't worked much with JSON and I'm using Google Maps Distance Matrix API to get generate some data I'd like to use.
I'd like to pull the number 14147 from duration.
{
"destination_addresses" : [ "Washington, DC, USA" ],
"origin_addresses" : [ "New York, NY, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "226 mi",
"value" : 364089
},
"duration" : {
"text" : "3 hours 56 mins",
"value" : 14147
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I've tried a few different things, here's what I tried last (data is just the array above):
String data = getOutputAsText(geoService);
JSONObject json = new JSONObject(data);
String duration = json.getJSONArray("rows").getString("duration");
Here's the console output:
org.json.JSONException: JSONObject["duration"] not found
I made sure to look around before posting but I haven't found anything that has been able to help me with this particular problem.
I want to pass the value from duration to my own web service, which I can do, I just don't know how to extract the value. Thank you in advance!
First of all, please have a look at this answer. Using org.json you can do smth. like that:
JSONObject obj = new JSONObject("Content of your string here");
JSONArray rows = obj.getJSONArray("rows");
for (int i = 0; i < rows.length(); i++) {
JSONArray elements = rows.getJSONObject(i).getJSONArray("elements");
for(int j = 0; j < elements.length(); j++) {
JSONObject element = elements.getJSONObject(j);
JSONObject duration = element.getJSONObject("duration");
int value = duration.getInt("value");
}
}
The code above has produced following output using your json String: 14147
P.S. You can make use of a library you wish. This one used here was purposed for the demonstrating.

updating json value of a nested json array in a json file | Java

I have this below json content in a file.
[
{
"prjId": 1,
"name" : "ABC",
"issueCounter": 7,
"issue": [
{
"id": 1,
"status" : "Closed",
"comment" : "blah blah blah",
"loggedBy": "shdkjdlsj"
},
{
"id": 2,
"status" : "Open",
"comment": "nothing",
"loggedBy": "xyz"
}
]
},
{
"prjId": 2,
"name" : "XYZ",
"issueCounter": 7,
"issue": [
{
"id": 3,
"status" : "Closed",
"comment": "jjjjjjjj",
"loggedBy": "klwm"
},
{
"id": 4,
"status" : "Closed",
"comment": "test test test",
"loggedBy": "NACK"
}
]
}]
I am able to parse this file and then traverse this json to get to the node where i wish to update. Upon reaching that point, i am confused on how to update it so that it would reflect on file on filesystem.
JSONParser parser = new JSONParser();
JSONArray rootArray = (JSONArray) parser.parse(new FileReader(pathToFile+fileName));
JSONObject project=null;
for (Object rootEntry : rootArray)
{
project = (JSONObject) rootEntry;
if( 1 == (Long) project.get("prjId"))
{
JSONArray issueArray = (JSONArray) project.get("issue");
for (Object issueEntry : issueArray)
{
JSONObject issue = (JSONObject) issueEntry;
System.out.println((Long) issue.get("id"));
if(2==(Long) issue.get("id"))
{
//now update the "comment" attribute here.
System.out.println("updated the comment: "+trckParam.getComment());
}
}
}
I have just the json reader till this point so do I construct a String as-and-when I traverse the nodes and when i reach the point I need to update, I update it (and construct the remainder of the nodes in this json object, (not to break from the loop)) and then write the entire reconstructed string to same file? Or is there a better approach where I can traverse the JSONObject and once i update it, push the entire object onto a file without constructing a String of entire file.
I still need to figure out a way to take either of the approach. So any pointers or direction will be greatly helpful.

creating JsonObject from JSONArray value in JAVA

I have a JsonArray Object like
JsonArray[0]= { "streetName" : "xyz", "wardName" : "12xz"}
JsonArray[1]= { "doorNumber" : "123", "plot" : "90z"}
JsonArray[2]= { "city" : "pqr", "district" : "nmc"}
JsonArray[3]= { "state" : "hisd", "country" : "kasps"}
I want to convert above JsonArray into JsonObject which will be like
{
"addresss":[ {
"streetName": "xyz",
"wardName": "12xz",
"doorNumber": "123",
"plot": "90z",
"city": "pqr",
"district": "nmc",
"state": "hisd",
"country": "kasps"
}]
}
I tried in different ways using Json Objcet put and traversing JSONarray and appending the value to String builder. No use. any one give me some idea. how to do that. Thanks for your help.

read json file and parse inner json array in java

{
"vers": 0.01,
"config": {
"rate": "perhr",
"valueColumns": [
"vCPU",
"ECU",
"memoryGiB",
"storageGB",
"linux"
],
"currencies": [
"USD"
],
"regions": [
{
"region": "us-east",
"instanceTypes": [
{
"type": "generalCurrentGen",
"sizes": [
{
"size": "t2.micro",
"vCPU": "1",
"ECU": "variable",
"memoryGiB": "1",
"storageGB": "ebsonly",
"valueColumns": [
{
"name": "linux",
"prices": {
"USD": "0.013"
}
}
]
},
{
"size": "t2.small",
"vCPU": "1",
"ECU": "variable",
"memoryGiB": "2",
"storageGB": "ebsonly",
"valueColumns": [
{
"name": "linux",
"prices": {
"USD": "0.026"
}
}
]
}
]
}
]
}
]
}
}
Hi, i wanted to read this json file. I tried various ways from google but getting a null at valuesColumns. I have to read sizes array and have to put in list.
I think it will help your cause if you format your json. As it is it's quite hard to read. Googling for a JSON beautifier quickly found me this one.
When working with JSON your browser console provides a nice environment for inspecting and playing with the data. I pasted it into the browser console and did (hit enter after each line):
var x = { ... paste JSON here ... }
x
x.config
x.config.valueColumns
This tells me that x is a JSON object, config is a JSON object and valueColumns is a JSON array
Now to java. Grab yourself a json library, and accessing valueColumns will be something like:
JSONObject x = new JSONObject("{ ... JSON string ... }");
JSONObject config = x.getJSONObject("config");
JSONArray valueColumns = config.getJSONArray("valueColumns");
You can then iterate over valueColumns and pull out what you need.
Note that the above only gets you to the first valueColumns array under config. By following the same principle you can go deeper into the structure and get out the valueColumns for the objects in the sizes array if that's what you're really after.
For parsing json to java there are simple step.
Below code snippet may help you.
// parse json to java
Object obj = parser.parse(s);
JSONObject json = (JSONObject) obj;
JSONObject o = (JSONObject) json.get("config");
//get json array.
JSONArray array = (JSONArray) o.get("valueColumns");
System.out.println(array.toJSONString());
//access element by index
System.out.println(array.get(0));

Categories