Parsing a complex JSON file - java

I need to parse a JSON file and put the data into a HTML table. I am using GWT for this application, the data shall be read from the file on the server side and passed to the client on page load.
The format for the JSONObjects in the file are as follows:
{
"Object 1": [
{ "value1": [ "subKey1", "subValue2" ], "value2": "val", "value3": { "key1": val1, "key2": val2, "key3": val3} },
{ "value2": [ "subKey1", "subValue2" ], "value2": "val", "value3": { "key1": val1, "key2": val2, "key3": val3} },
....
....
],
"Object 2": [
{ "value1": [ "subKey1", "subValue2" ], "value2": "val", "value3": { "key1": val1, "key2": val2, "key3": val3} },
{ "value2": [ "subKey1", "subValue2" ], "value2": "val", "value3": { "key1": val1, "key2": val2, "key3": val3} },
....
....
],
....
}
Up until now, I have only done simple JSON parsing. The problem I am having here is that the data I am working with has a unique name for each object so I cannot seem to parse them into an array of JSONObjects.
I have attempted to parse them (using JSON simple) this way but I am throwing an error.
try {
JSONParser parser = new JSONParser();
JSONObject obj;
obj = (JSONObject) parser.parse(new FileReader("file.json"));
JSONArray array = new JSONArray();
array.add(obj.get("Object1"));
array.add(obj.get("Object2"));
array.add(obj.get("Object3"));
array.add(obj.get("Object4"));
JSONObject jo;
for (Object o : array) {
jo = (JSONObject) o;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
But this throws an error:
org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
Another method from my understanding is to create a POJO class for the objects but since each JSONObject has a different identifier, does that mean each object must have its own unique class? Some JSON2Java methods I have used just create a new class for each of them.

You can check the instance of the Object before casting it:
for (Object obj : array) {
if (obj instanceof JSONArray) {
// It's an array
yourJsonArray = (JSONArray)obj;
} else if (obj instanceof JSONObject) {
// It's an object
yourJsonObject = (JSONObject)obj;
} else {
// It's string, number...
}
}

Related

parse a string object to a JSONObject

I need to parse a string that contains data of JSON file into a JSONObject and iterate over it's content to get it's keys and values for further treatement after. I'am stuck at parsing the content of a file after transforming it to a string. I tried to user parse() , quote() but it seems i'am missing a detail and i'am making a major mistake.
This is a snippet of the json file i treat :
{
{
"id":0,
"name": "project1",
"couverage": "100",
"completness": "44.8",
"consistency": "46",
}
{
"id":1,
"name": "project2",
"couverage": "100",
"completness": "44.8",
"consistency": "46",
}
{
"id":2,
"name": "project3",
"couverage": "100",
"completness": "44.8",
"consistency": "46",
}
}
and this is the code i developed
public void readfromJsonFile(File jsonFile, long readTimeStamp) {
logger.info("Read from JSON file: {}", jsonFile.getName());
try{
//Read File Content
String content = new String(Files.readAllBytes(jsonFile.toPath()));
JSONParser jsonParser = new JSONParser(content);
JSONObject obj = (JSONObject) jsonParser.parse();
JSONArray key = obj.names();
for (int i = 0; i < key.length (); ++i) {
String keys = key.getString(i);
System.out.println(keys);
String value = obj.getString (keys);
System.out.println(value);
}catch (Exception e) {
logger.error("Failed to parse JSON File: {}", jsonFile.getName());
}
}
You can use Jackson Databind as well.
Create a POJO class. For example :
public class POJO {
private int id;
private String name;
private String couverage;
private String completness;
private String consistency;
// getters, setters and constructors
}
Modify the JSON in the file.
[
{
"id":0,
"name": "project1",
"couverage": "100",
"completness": "44.8",
"consistency": "46"
},
{
"id":1,
"name": "project2",
"couverage": "100",
"completness": "44.8",
"consistency": "46"
},
{
"id":2,
"name": "project3",
"couverage": "100",
"completness": "44.8",
"consistency": "46"
}
]
Code :
public void readfromJsonFile(File jsonFile, long readTimeStamp) {
logger.info("Read from JSON file: {}", jsonFile.getName());
try {
ObjectMapper objectMapper = new ObjectMapper();
POJO[] pojos = objectMapper.readValue(jsonFile, POJO[].class);
for (int i = 0; i < pojos.length; ++i) {
System.out.println(pojos[i].getId());
}
} catch (Exception e) {
logger.error("Failed to parse JSON File: {}", jsonFile.getName());
}
}
Try it like this
JSONArray array_= new JSONArray(content);
JSONObject obj = (JSONObject) array_.get(0);// or any index
then you can use the Object.

Convert Json payload to java objects

I need to implement below json payload to java object including JSONArray and JSONObject
I tried using below java code in order to implement the same
DWYT_productOrderResponse CreateProductOrderResponse = new DWYT_productOrderResponse();
ResultHeader rslthdr = new ResultHeader();
JSONObject productOrder = new JSONObject();
JSONArray orderIt = new JSONArray();
JSONObject produt = new JSONObject();
// List<ProductCharacteristic> ProductChara = new ArrayList<ProductCharacteristic>();
Map ProductChara = new LinkedHashMap();
//Map orderItem = new LinkedHashMap();
// OrderIteam[] orderItem;
if (1 == 1) {
String output = null;
try {
productOrder.put("externalId", CreateOrderReq.getProductOrder().getExternalId());
productOrder.put("description", CreateOrderReq.getProductOrder().getDescription());
ProductChara.put("name", "CustomerName");
ProductChara.put("value", CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getCustomerName());
ProductChara.put("name", "CustomerContactNumber");
ProductChara.put("value", CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getCustomerContactNumber());
ProductChara.put("name", "CRMAddress");
ProductChara.put("value", CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getCRMAddress());
ProductChara.put("name", "CustomerEmail");
ProductChara.put("value", CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getCustomerEmail());
ProductChara.put("name", "CustomerGovetID");
ProductChara.put("value", CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getCustomerGovtID());
ProductChara.put("name", "ODBNo");
ProductChara.put("value", CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getODBNO());
produt.put("productCharacteristic", ProductChara);
produt.put("product", produt);
orderIt.put(produt);
productOrder.put("orderItem", orderIt);
productOrder.put("productOrder", productOrder);
} catch (JSONException e) {
e.printStackTrace();
}
}
here is the result of json payload of the above code
{
"externalId":"CRM000000912",
"description":"Activation Request",
"orderItem":[
{
"productCharacteristic":{
"name":"CustomerName",
"value":"xxxx",
"name":"CustomerContactNumber",
"value":"5600000232",
"name":"CRMAddress",
"value":"xxxxxxx",
"name":"CustomerEmail",
"value":"xxx#xx.xxx",
"name":"CustomerGovetID",
"value":"1223232323232322",
"name":"ODBNo",
"value":"RYH-736834-JKS"
}
}
]
}
here is the json payload that I want to parse
{
"externalId": " 12345678",
"orderItem": [{
"product": {
"productCharacteristic": [{
"name": "CustomerName",
"value": "someone"
}, {
"name":
"CustomerContactNumber",
"value": "13524687502"
}, {
"name": "CRMAddress",
"value": "xxxxxx"
}, {
"name": "CustomerEmail ",
"value": "XXX"
}, {
"name": " CustomerGovet.ID",
"value": "XXX"
}, {
"name": " ODBNo.",
"value": "XXX"
}
]
}
}
]
}
Is there any easy way or java code that can help me to get the expected output.
SOLVED: now I got the expected json payload after adding some enhancement to my code
try {
productOrder.put("externalId", CreateOrderReq.getProductOrder().getExternalId());
productOrder.put("description", CreateOrderReq.getProductOrder().getDescription());
ProductChara.put("name","CustomerName");
ProductChara.put("value",CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getCustomerName());
ProductCharaArray.put(ProductChara);
ProductChara.put("name","CustomerContactNumber");
ProductChara.put("value",CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getCustomerContactNumber());
ProductCharaArray.put(ProductChara);
ProductChara.put("name","CRMAddress");
ProductChara.put("value",CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getCRMAddress());
ProductCharaArray.put(ProductChara);
ProductChara.put("name","CustomerEmail");
ProductChara.put("value",CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getCustomerEmail());
ProductCharaArray.put(ProductChara);
ProductChara.put("name","CustomerGovetID");
ProductChara.put("value",CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getCustomerGovtID());
ProductCharaArray.put(ProductChara);
ProductChara.put("name","ODBNo");
ProductChara.put("value",CreateOrderReq.getProductOrder().getOrderItem().getProduct().getProductCharacteristic().getODBNO());
ProductCharaArray.put(ProductChara);
produt.put("productCharacteristic",ProductCharaArray);
orderItm.put("product",produt);
orderItemArray.put(orderItm);
productOrder.put("orderItem", orderItemArray);
System.out.println(productOrder.toString());
} catch (JSONException e) {
e.printStackTrace();
}

How to access nested elements of JSON data in Java?

I'm getting JSON data from a url and I want to show the data on my website. I am successfully showing all JSON data except JSON Hierarchy (JSON Object) data. I am able to access JSONArray person and error data. But, I am not able to access hierarchy (JSON Object) updated data.
I want to access updated.time.
import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
public class ParseJson1 {
public static void main(String[] args) {
String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2";
/*
{
"person": [
{
"name": "John",
"city": "Mumbai"
},
{
"name": "Rahul",
"city": "Delhi"
},
{
"name": "Sanjana",
"city": "Amritsar"
},
{
"name": "Anjali",
"city": "Hyderabad"
},
{
"name": "Mukund",
"city": "Bangalore"
},
{
"name": "Raunak",
"city": "Patna"
}
],
"updated": {
"time": "14:17:48",
"date": "2016-04-10"
},
"error": "2353"
}
*/
try {
String genreJson = IOUtils.toString(new URL(url));
JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
// get the error
System.out.println(genreJsonObject.get("error"));
//Get Array Values
JSONArray genreArray = (JSONArray) genreJsonObject.get("person");
// get the first genre
JSONObject firstGenre = (JSONObject) genreArray.get(0);
System.out.println(firstGenre.get("name"));
// get the Second
JSONObject firstGenre = (JSONObject) genreArray.get(1);
System.out.println(firstGenre.get("name"));
// get the third
JSONObject firstGenre = (JSONObject) genreArray.get(2);
System.out.println(firstGenre.get("city"));
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}
This json Result appears what you got from your api URL . Right ??
{
"person":[
{
"name":"John",
"city":"Mumbai"
},
{
"name":"Rahul",
"city":"Delhi"
},
{
"name":"Sanjana",
"city":"Amritsar"
},
{
"name":"Anjali",
"city":"Hyderabad"
},
{
"name":"Mukund",
"city":"Bangalore"
},
{
"name":"Raunak",
"city":"Patna"
}
],
"updated":{
"time":"14:17:48",
"date":"2016-04-10"
},
"error":"2353"
}
Now Here is a Code how to Iterate or parse your json Object. I Suppose that above Result json is stored in a String Variable String genreJson as per Your Code.
Here I wrote a method to solve your Problem. You may take a reference of it and may try your own code.
public void testYourJSON(String genreJson){
JSONParser parser=new JSONParser(); //parser used to parse String to Correct Json format.
JSONObject obj_ComplexData = (JSONObject) parser.parse(genreJson); // Now Your String Converted to a JSONObject Type.
//person tag Array Data is fetched and Stored into a JSONArray Object.
JSONArray obj_arrayPersonData = (JSONArray) parser.parse(obj_ComplexData.get("person").toString());
for (Object person : obj_arrayPersonData ) { //Iterate through all Person Array.
System.out.println(person.get("name"));
System.out.println(person.get("city"));
}
//Select "updated" Tag Json Data.
JSONObject obj_Updated = (JSONObject) parser.parse(obj_ComplexData.get("updated").toString());
System.out.println(obj_Updated.get("time")); //display time tag.
System.out.println(obj_Updated.get("date")); //display date tag.
System.out.println(obj_Updated.get("error")); //display Your Error.
}
Try this
public static String[] getInfo(String url)
{
String result=//I am assuming your json response is in result
String[] titles=null;
try {
JSONObject jsonObject=new JSONObject(result);
JSONObject temp=null;
JSONArray jsonArray=jsonObject.getJSONArray("person");
int length=jsonArray.length();
person=new String[length];
for (int i=0;i<length;i++){
temp= (JSONObject) jsonArray.get(i);
titles[i]=temp.getString("name")+temp.getString("city");
}
} catch (JSONException e) {
e.printStackTrace();
}
return titles;
}
This works fine, if you face any problem write in comments.
Happy coding!!

Json array manipulation in android

If I have a Json array object that looks like this:
[
{"values here"},
{"values here"},
{"values here"}
]
And I want a Json array object that looks like this:
{
"key1":"value1","key2":"value2","key3":"value3"
:[
{"values here"},
{"values here"},
{"values here"}
]
}
Is it possible for me to insert another json object at the front of all the elements in the array and encloses them.
Use the following Example
JSONObject student1 = new JSONObject();
try {
student1.put("id", "3");
student1.put("name", "NAME OF STUDENT");
student1.put("year", "3rd");
student1.put("curriculum", "Arts");
student1.put("birthday", "5/5/1993");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject student2 = new JSONObject();
try {
student2.put("id", "2");
student2.put("name", "NAME OF STUDENT2");
student2.put("year", "4rd");
student2.put("curriculum", "scicence");
student2.put("birthday", "5/5/1993");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(student1);
jsonArray.put(student2);
JSONObject studentsObj = new JSONObject();
studentsObj.put("Students", jsonArray);
String jsonStr = studentsObj.toString();
System.out.println("jsonString: "+jsonStr);
above Example taken from Here
I'm not sure what you mean by "encloses".
You can have the first element of the array be your object.
[
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
"values here",
"values here",
"values here"
]
You can also have an object like
{
"first": {
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
"rest": [
"values here",
"values here",
"values here"
]
}

Parse a nested JSON using gson

{
"Response": {
"MetaInfo": {
"Timestamp": "2011-11-21T14:55:06.556Z"
},
"View": [
{
"_type": "SearchResultsViewType",
"ViewId": 0,
"Result": [
{
"Relevance": 0.56,
"MatchQuality": {
"Country": 1,
"State": 1,
"County": 1,
"City": 1,
"PostalCode": 1
},
"Location": {
"LocationType": "point",
"DisplayPosition": {
"Latitude": 50.1105,
"Longitude": 8.684
},
"MapView": {
"_type": "GeoBoundingBoxType",
"TopLeft": {
"Latitude": 50.1194932,
"Longitude": 8.6699768
},
"BottomRight": {
"Latitude": 50.1015068,
"Longitude": 8.6980232
}
},
"Address": {
"Country": "DEU",
"State": "Hessen",
"County": "Frankfurt am Main",
"City": "Frankfurt am Main",
"District": "Frankfurt am Main",
"PostalCode": "60311",
"AdditionalData": [
{
"value": "Germany",
"key": "CountryName"
}
]
}
}
}
]
}
]
}
}
I am trying to retrieve the postal code from the above JSON. I am using gson to parse it. I am very new to JSON and from what i read from all the posts here(some very similar to this), I understood that the fields name should be as it is. So I understand i have to make 4 classes viz Response, view, Result and Address. I made them static nested classes, but I am only getting null value as output. In the next JSON, I have multiple addresses. But I am stuck on this single response.
For a short example, I try to retrieve Timestamp with this code, but it gives me a null value
public class ParseJSON {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("try.json"));
Gson gson = new GsonBuilder().create();
Pojo pojo = gson.fromJson(br,Pojo.class);
System.out.println(Pojo.Response.MetaInfo.Timestamp);
br.close();
}
}
class Pojo {
public Pojo() { }
static class Response{
static class MetaInfo {
static public String Timestamp;
public String getTimestamp() {
return Timestamp;
}
}
}
}
If you only need the "PostalCode", you could use JsonParser instead of having a bunch of classes:
JsonParser jsonParser = new JsonParser();
JsonObject address = jsonParser.parse(json)
.getAsJsonObject().get("Response")
.getAsJsonObject().getAsJsonArray("View").get(0)
.getAsJsonObject().getAsJsonArray("Result").get(0)
.getAsJsonObject().get("Location")
.getAsJsonObject().getAsJsonObject("Address");
String postalCode = address.get("PostalCode").getAsString();
or for all results:
JsonArray results = jsonParser.parse(json)
.getAsJsonObject().get("Response")
.getAsJsonObject().getAsJsonArray("View").get(0)
.getAsJsonObject().getAsJsonArray("Result");
for (JsonElement result : results) {
JsonObject address = result.getAsJsonObject().get("Location").getAsJsonObject().getAsJsonObject("Address");
String postalCode = address.get("PostalCode").getAsString();
System.out.println(postalCode);
}
To make your Timestamp example work, try:
public class ParseJSON {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("try.json"));
Gson gson = new GsonBuilder().create();
Pojo pojo = gson.fromJson(br, Pojo.class);
System.out.println(pojo.Response.MetaInfo.Timestamp);
br.close();
}
}
class Pojo {
Response Response = new Response();
}
class Response {
MetaInfo MetaInfo = new MetaInfo();
}
class MetaInfo {
String Timestamp;
}

Categories