Reputation: 3593
I've got JSON file, which I want to parse. The JSON file ("myfile") has format as follows:
{
"LanguageLevels": {
"1": "Początkujący",
"2": "ŚrednioZaawansowany",
"3": "Zaawansowany",
"4": "Ekspert"
}
}
I want to retrieve value (ŚrednioZaawansowany) of Key 2 from Language Levels.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonSimpleExample {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("myfile");
JSONObject jsonObject = (JSONObject) obj;
JSONObject jsonChildObject = (JSONObject)jsonObject.get("LanguageLevels");
What to do next? How I can iterate over it?
Upvotes: 21
Views: 176437
Reputation: 1282
Here is an example of retrieving nested JSON object.
Department and Product are model classes.
Department class holds department
as a String and products
as ArrayList of Product
Product class holds name
as a String
depts
and products
are ArrayList of corresponding model classes
String jsonDataString = readJSONDataFromFile();
JSONArray jsonArray = new JSONArray(jsonDataString);
for (int i=0; i<jsonArray.length(); ++i) {
JSONObject departmentJSONObject = jsonArray.getJSONObject(i);
String deptName = departmentJSONObject.getString("department");
JSONArray productsJSONArray = departmentJSONObject.getJSONArray("products");
for (int j =0; j <productsJSONArray.length();j++){
JSONObject productJSONObject = productsJSONArray.getJSONObject(j);
String prodName = productJSONObject.getString("name");
Product product = new Product(prodName);
products.add(product);
}
Department department = new Department(deptName, products);
depts.add(department);
Here is my raw json file
[
{
"department": "Cold Drink",
"products": [
{
"name": "lemonade",
"img": "some_url"
},
{
"name": "Oj",
"img": "some_url"
}
]
},
{
"department": "CD2",
"products": [
{
"name": "lemonade2",
"img": "some_url2"
},
{
"name": "oj2",
"img": "some_url2"
}
]
},
{
"department": "CD3",
"products": [
{
"name": "lemonade3",
"img": "some_url3"
},
{
"name": "oj3",
"img": "some_url3"
}
]
}
]
Upvotes: 0
Reputation: 41
Try this, you can parse nested JSON
public static String getJsonValue(String jsonReq, String key) {
JSONObject json = new JSONObject(jsonReq);
boolean exists = json.has(key);
Iterator<?> keys;
String nextKeys;
String val = "";
if (!exists) {
keys = json.keys();
while (keys.hasNext()) {
nextKeys = (String) keys.next();
try {
if (json.get(nextKeys) instanceof JSONObject) {
return getJsonValue(json.getJSONObject(nextKeys).toString(), key);
} else if (json.get(nextKeys) instanceof JSONArray) {
JSONArray jsonArray = json.getJSONArray(nextKeys);
int i = 0;
if (i < jsonArray.length()) do {
String jsonArrayString = jsonArray.get(i).toString();
JSONObject innerJson = new JSONObject(jsonArrayString);
return getJsonValue(innerJson.toString(),key);
} while (i < jsonArray.length());
}
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
val = json.get(key).toString();
}
return val;
}
Upvotes: 1
Reputation: 756
Maybe you're not using the latest version of a JSON for Java Library.
json-simple
has not been updated for a long time, while JSON-Java
was updated 2 month ago.
JSON-Java
can be found on GitHub, here is the link to its repo: https://github.com/douglascrockford/JSON-java
After switching the library, you can refer to my sample code down below:
public static void main(String[] args) {
String JSON = "{\"LanguageLevels\":{\"1\":\"Pocz\\u0105tkuj\\u0105cy\",\"2\":\"\\u015arednioZaawansowany\",\"3\":\"Zaawansowany\",\"4\":\"Ekspert\"}}\n";
JSONObject jsonObject = new JSONObject(JSON);
JSONObject getSth = jsonObject.getJSONObject("LanguageLevels");
Object level = getSth.get("2");
System.out.println(level);
}
And as JSON-Java
open-sourced, you can read the code and its document, they will guide you through.
Hope that it helps.
Upvotes: 35
Reputation: 149
You will have to iterate step by step into nested JSON.
for e.g a JSON received from Google geocoding api
{
"results" : [
{
"address_components" : [
{
"long_name" : "Bhopal",
"short_name" : "Bhopal",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Bhopal",
"short_name" : "Bhopal",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Madhya Pradesh",
"short_name" : "MP",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "India",
"short_name" : "IN",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Bhopal, Madhya Pradesh, India",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 23.3326697,
"lng" : 77.5748062
},
"southwest" : {
"lat" : 23.0661497,
"lng" : 77.2369767
}
},
"location" : {
"lat" : 23.2599333,
"lng" : 77.412615
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 23.3326697,
"lng" : 77.5748062
},
"southwest" : {
"lat" : 23.0661497,
"lng" : 77.2369767
}
}
},
"place_id" : "ChIJvY_Wj49CfDkR-NRy1RZXFQI",
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}
I shall iterate in below given fashion to "location" : { "lat" : 23.2599333, "lng" : 77.412615
//recieve JSON in json object
JSONObject json = new JSONObject(output.toString());
JSONArray result = json.getJSONArray("results");
JSONObject result1 = result.getJSONObject(0);
JSONObject geometry = result1.getJSONObject("geometry");
JSONObject locat = geometry.getJSONObject("location");
//"iterate onto level of location";
double lat = locat.getDouble("lat");
double lng = locat.getDouble("lng");
Upvotes: 14
Reputation: 721
To see all keys of Jsonobject use this
String JSON = "{\"LanguageLevels\":{\"1\":\"Pocz\\u0105tkuj\\u0105cy\",\"2\":\"\\u015arednioZaawansowany\",\"3\":\"Zaawansowany\",\"4\":\"Ekspert\"}}\n";
JSONObject obj = new JSONObject(JSON);
Iterator iterator = obj.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
System.out.pritnln(key);
}
Upvotes: 1
Reputation: 7571
You can see that JSONObject extends a HashMap
, so you can simply use it as a HashMap:
JSONObject jsonChildObject = (JSONObject)jsonObject.get("LanguageLevels");
for (Map.Entry in jsonChildOBject.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Upvotes: 7
Reputation: 7389
JSONArray jsonChildArray = (JSONArray) jsonChildArray.get("LanguageLevels");
JSONObject secObject = (JSONObject) jsonChildArray.get(1);
I think this should work, but i do not have the possibility to test it at the moment..
Upvotes: 2