Parsing JSON in Java is same as with another language, but a little bit complex. I use JSON-Simple for parsing JSON and accessing nested JSON array and Object. For example, I have JSON nested structure like :
1 2 3 4 5 6 7 8 | { "items": [ { "kind": "shopping#product", "id": "tag:google.com,2010:shopping/products/10048/187970250782485989", "product": { "country": "US", "language": "en", |
Now we will access “items” which have array() inside.
1 2 3 4 5 6 | JSONObject responseObject = new JSONObject(resp); JSONArray array = responseObject.getJSONArray("items"); for(int i=0; i<array.length(); i++) { // Do something here …. } |
We can show “kind” value in “items” by :
1 2 3 4 5 6 | JSONObject responseObject = new JSONObject(resp); JSONArray array = responseObject.getJSONArray("items"); for(int i=0; i<array.length(); i++) { String title = array.getJSONObject(i).getString("kind"); } |
Then, we need to access “country” value inside “product”.
1 2 3 4 5 6 7 8 9 | JSONObject responseObject = new JSONObject(resp); JSONArray array = responseObject.getJSONArray("items"); for(int i=0; i<array.length(); i++) { String title = array.getJSONObject(i).getString("kind"); JSONObject product = new JSONObject(array.getJSONObject(i).getString("product")); String country = product.getString("country"); } |
Seems it’s a little bit hard it first time, but soon you will adapt and see it easy to do 🙂