-4

[{"name":"RAJGOWTHAMAN R","branch":"B.Tech - Information Technology","details":[{"semester":"6","subcode":"10 IT 611","subname":"Object Oriented Analysis and Design","grade":"C","result":"Pass"},{"semester":"6","subcode":"10 IT 612","subname":"Visual Programming","grade":"C","result":"Pass"},{"semester":"6","subcode":"10 IT 613","subname":"Web Technology","grade":"E","result":"Pass"},{"semester":"6","subcode":"10 IT 614","subname":"Cryptography and Network Security","grade":"E","result":"Pass"},{"semester":"6","subcode":"10 IT 615","subname":"System Software","grade":"D","result":"Pass"},{"semester":"6","subcode":"10 IT 6P1","subname":"Visual Programming Laboratory","grade":"A","result":"Pass"},{"semester":"6","subcode":"10 IT 6P2","subname":"CASE Tools Laboratory","grade":"C","result":"Pass"},{"semester":"6","subcode":"10 IT 6P3","subname":"Web Technology Laboratory","grade":"S","result":"Pass"},{"semester":"6","subcode":"10 IT E13","subname":"Software Quality Management","grade":"RA","result":"Fail"}]}]

how can I parse the above json

  • 5
    Please make a cursory attempt to research before asking. First result for `java parse json`: [How to parse JSON in Java](http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) – tnw Oct 07 '15 at 20:13

1 Answers1

1

There are a number of JSON libraries available in Java:

Here's code snippet to parse the JSON string using json-simple:

import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.JSONValue;

...
String jsonLine = "[{ ... }]";
// first have to parse JSON into object
Object obj = JSONValue.parse(jsonLine);
JSONArray array = (JSONArray)obj;
JSONObject value = (JSONObject)array.get(0);
// JSONObject extends HashMap so can access properties as any Map
System.out.println("keys=" + value.keySet());
JSONArray details = (JSONArray) value.get("details");
// do something with details object

From your example, this would output:

keys=[name, details, branch]

json-simple has many examples to decode JSON:
https://github.com/fangyidong/json-simple/wiki

Using gson the code is nearly identical:

JsonElement jelement = new JsonParser().parse(jsonLine);
JsonElement value = jelement.getAsJsonArray().get(0);
JsonArray details = value.getAsJsonObject().get("details").getAsJsonArray();
CodeMonkey
  • 22,825
  • 4
  • 35
  • 75
  • No problems with the simple json...But what about the nested array json – Gautam Rajendran Oct 07 '15 at 20:55
  • For nested arrays you access the "details" value then cast to JSONArray then iterate over the values. Check out the [javadoc](http://juliusdavies.ca/json-simple-1.1.1-javadocs/org/json/simple/JSONObject.html) for json-simple for API usage. – CodeMonkey Oct 07 '15 at 21:03