1

How do you parse a nested JSON file like below using Processing JSON object? I am trying to figure out how to parse JSON that is multi-level.

{
  "info": {
    "description": "COCO 2014 Dataset",
    "url": "http://cocodataset.org",
    "version": "1.0",
    "year": 2014,
    "contributor": "COCO Consortium",
    "date_created": "2017/09/01"
  },
  "images": [
    {
      "license": 5,
      "file_name": "COCO_train2014_000000057870.jpg",
      "coco_url": "http://images.cocodataset.org/train2014/COCO_train2014_000000057870.jpg",
      "height": 480,
      "width": 640,
      "date_captured": "2013-11-14 16:28:13",
      "flickr_url": "http://farm4.staticflickr.com/3153/2970773875_164f0c0b83_z.jpg",
      "id": 57870
    },
2

2 Answers 2

3

Have a look at JSONObject and JSONArray to see the available methods bellow on each page, each with documentation and examples.

Regarding your structure, here's a quick snippet on how you might access nested JSON objects and arrays:

// assume data is a JSONObject pointing to the loaded json data (via loadJSONObject / JSONObject.parse(), etc.

// access the info object
JSONObject info = data.getJSONObject("info");
// access the images array object
JSONArray images = data.getJSONArray("images");
// access a string inside an object
println(info.getString("description"));
// access a JSON object inside a JSON array
JSONObject firstImage = images.getJSONObject(0);

// acess an integer
println(firstImage.getInt("id"));
// ... and a string again
println(firstImage.getString("flickr_url"));

If you name your loaded JSONObject variable data, paste the the snippet above and run, it should print:

COCO 2014 Dataset
57870
http://farm4.staticflickr.com/3153/2970773875_164f0c0b83_z.jpg
Sign up to request clarification or add additional context in comments.

Comments

0

You can use Gson to parse/deserialize to model class.

Or if you want to parse manually, then you have to parse a json object first and then you have to parse it again from a parsed json.

Eg.

JsonObject jsonObject = new JsonObject(jsonString);
JsonObject infoObject = jsonObject.getJsonObject("info");
String description = infoObject.getString("description");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.