Parsing Nested JSON Array with json-simple [duplicate] - java

This question already has answers here:
How do I parse a JSONArray in Java with Json.simple?
(3 answers)
Closed 7 years ago.
Trying to use json simple to parse data from rest service. The response looks like:
{
"locations": [
"city" : "San Jose",
"state" : "Ca",
"job" : {
"site" : "Main Processing",
"region" : "USA"
}
]
}
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONArray array = (JSONArray) jsonObject.get("locations");
for(int i = 0; i < array.size(); i++) {
String site = array.getJSONObject(i).getString("site");
}
My issue is I am having trouble getting a reference to the job element from JSONArray object. The "locations" reference is basic parsing but the "job" reference is giving me issue when its defined inside an array.
Also getJSONObject does not seem to be a valid method to JSONArray.
Can this be done with the json-simple library?

The getJSONObject method is provided by the org.json.JSONArray class. (without using json-simple). I can not find it in the json-simple doc. So using the org.json.* package import, you can do:
JSONObject jsonObject = new JSONObject(jsonAsString);
JSONArray array = jsonObject.getJSONArray("locations");
//You should check that array.length() >= 3
JSONObject job = array.getJSONObject(2);
String site = job.getString("site");

Related

JSON : how to save JSON Array using Java and loop till last JSON Object

I'm new to JSON and have below file. I have to save the array "steps" in java and need to loop the objects "duration" , "status" and "Keyword".
"steps": [
{
"result": {
"duration": 7128811788,
"status": "passed"
},
"line": 5,
"name": "The Browser is Launched and Smart Business URL is loaded",
"match": {
"location": "Common_Login.the_Browser_is_Launched_and_Smart_Business_URL_is_loaded()"
},
"keyword": "Given "
},]
I tried below but didn't worked.
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("./target/JSON/Output.json"));
JSONArray jsonArray = (JSONArray) obj;
System.out.println(jsonArray);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObjectRow = (JSONObject) jsonArray.get(i);
name = (String) jsonObjectRow.get("duration");
id = (String) jsonObjectRow.get("status");
uri = (String) jsonObjectRow.get("name");
status = (String) jsonObjectRow.get("location");
}
Refer here.
There are so many libraries build in for doing this task. But look at the question above.
If you want to use the built-in class from Java you can have a look here:
https://stackoverflow.com/a/17399110/3977134
You are missing the part from the parseJson function in the referenced answer.
For simplicity I'd suggest to you to use org.json which is just one of many good libraries to use for JSON parsing in Java. If you are interested see here:
Parse JSON with org.json
Parsing JSON in Java Using org.json

Getting a Value from a JsonArray using gson

I have searched everywhere and cannot find out how to do this, I'm super stuck. I have NO experience with JSON files, so spoon feeding is appreciated along with an explanation.
I have this JSON text here for testing:
{
"id":"4566e69fc90748ee8d71d7ba5aa00d20",
"properties":
[
{
"name":"textures",
"value":"eyJ0aW1lc3RhbXAiOjE0ODI4ODAxNDMwNzYsInByb2ZpbGVJZCI6IjQ1NjZlNjlmYzkwNzQ4ZWU4ZDcxZDdiYTVhYTAwZDIwIiwicHJvZmlsZU5hbWUiOiJUaGlua29mZGVhdGgiLCJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTNlODFiOWUxOWFiMWVmMTdhOTBjMGFhNGUxMDg1ZmMxM2NkNDdjZWQ1YTdhMWE0OTI4MDNiMzU2MWU0YTE1YiJ9LCJDQVBFIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMjJiOWM1ZWE3NjNjODZmYzVjYWVhMzNkODJiMGZhNjVhN2MyMjhmZDMyMWJhNTQ3NjZlYTk1YTNkMGI5NzkzIn19fQ==",
},
],
"name":"Thinkofdeath",
}
I currently have this:
JsonElement playerProfile = new JsonParser().parse(jsonLine);
JsonObject jsonProfile = playerProfile.getAsJsonObject();
JsonArray properties = jsonProfile.getAsJsonArray("properties");
Which returns
[
[
{
"name":"textures",
"value":"eyJ0aW1lc3RhbXAiOjE0ODI4ODAxNDMwNzYsInByb2ZpbGVJZCI6IjQ1NjZlNjlmYzkwNzQ4ZWU4ZDcxZDdiYTVhYTAwZDIwIiwicHJvZmlsZU5hbWUiOiJUaGlua29mZGVhdGgiLCJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTNlODFiOWUxOWFiMWVmMTdhOTBjMGFhNGUxMDg1ZmMxM2NkNDdjZWQ1YTdhMWE0OTI4MDNiMzU2MWU0YTE1YiJ9LCJDQVBFIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMjJiOWM1ZWE3NjNjODZmYzVjYWVhMzNkODJiMGZhNjVhN2MyMjhmZDMyMWJhNTQ3NjZlYTk1YTNkMGI5NzkzIn19fQ==",
},
]
Of course. How do I get the "value" from this JsonArray? Note I'm using Google's API, Gson
You can get values using:
JsonObject propertiesJson = properties.get(0);
String value = propertiesJson.getString("value");
array is JsonArray object from com.google.gson library
for (int i=0; i<array.size(); i++) {
JsonObject json = array.get(i).getAsJsonObject();
String value = json.get("key").getAsString();
}

Android Json parsing with multiple JsonArray's [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 7 years ago.
I am trying to parse JSON data which is like:
{
"name1": "xyz",
"data":[{
"education": {
"School": "xyz",
"ug": "xyz",
"Activities": [{
...
}],
"Prizes": [{
...
}],
"Curriculum":[{
...
}]
}
}]
}
How can I fetch the JSONArray of activities, prizes, curriculum values?
If you just want the values of the first element (you are looking at an array so you may want all the elements) you can try this:
String src = " { ... } "; //your json
JSONObject mainObject= new JSONObject(src);
JSONArray dataArray= mainObject.getJSONArray("data");
JSONObject firstDataObject = dataArray.getJSONObject(0); //get the first element
JSONObject educationObject = firstDataObject.getJSONObject("education");
JSONArray activitiesArray = educationObject.getJSONArray("Activities");
//do something with the array. Ex: activitiesArray.getJSONObject(0);
JSONArray prizesArray = educationObject.getJSONArray("Prizes");
//do something with the array
JSONArray curriculumArray = educationObject.getJSONArray("Curriculum");
//do something with the array

How do I parse a JSON array in Java? [duplicate]

This question already has answers here:
Parsing JSON Object in Java [duplicate]
(5 answers)
Closed 7 years ago.
I have the following JSON text and would like to get the values "detest" and "dislike".
{
"noun": {
"syn": [
"hatred",
"emotion"
],
"ant": [
"love"
]
},
"verb": {
"syn": [
"detest",
"dislike"
],
"ant": [
"love"
]
}
}
I've tried parsing it using the org.json library with the following:
JSONArray obj = new JSONObject(String);
JSONArray arr = obj.getJSONArray("syn");
But I can't seem to access the array this way.
Any help is greatly appreciated.
The following is related to the JSON.simple library.
You need a JSONParser instance to get a JSONObject value from your String object.
JSONObject data;
try {
JSONParser helper = new JSONParser();
data = (JSONObject)helper.parse(String);
} catch (ParseException parse) {
// Invalid syntax
return;
}
// Note that these may throw several exceptions
JSONObject node = (JSONObject)data.get("verb");
JSONArray array = (JSONArray)node.get("syn");

How to parse JSON in java and what are the differences between JSONObect and JSONArray? [duplicate]

This question already has answers here:
Converting JSON data to Java object
(14 answers)
Closed 8 years ago.
{
"users":[ {
"user":"hi","password":"hi"
}, {
"user":"test","password":"test"
}
]
}
How to parse this type of JSON Objects?
Please help..
You need to use a json library like gson, jsonlib or jackson.
JSONObject: it is a hash object like Map where key value pairs are used
JSONArray: It is a collection of objects like List
JSONObject works like a map with key-value pairs. Eg. Code looks like below :
JSONObject obj=new JSONObject();
obj.put("name","Hello");
obj.put("nickname","Hi");
StringWriter out = new StringWriter();
obj.writeJSONString(out);
String jsonText = out.toString();
System.out.print(jsonText);
JSONArray works like a list , Eg, code below:
JSONArray list = new JSONArray();
list.add("Hello");
list.add(new Integer(100));
System.out.print(list);
You can differentiate the JSONArray & JSONObject as below:
JSONArray
A JSONArray is an ordered sequence of values. Its external text form is a string wrapped in square brackets with commas separating the values.
[ {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
{"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
]
JSONObject
A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names.
{"bindings": [
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
{"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
]
};
You can parse the JSONObject as below:
JSONObject JsonObject = new JSONObject(json);
JSONArray JsonArray_ = JsonObject .getJSONArray("users");
for (int i = 0; i < numberOfItems; i++) {
JSONObject record= JsonArray_photo.getJSONObject(i);
parsedObject.user = record.getString("user"); //its the same for all fields
parsedObject.password = record.getString("password");
map.add(parsedObject);
}

Categories

Resources