SuperCow
SuperCow

Reputation: 1613

Java How to access JSON inner child array

I have a JSON that has a similar structure to the one below (end of post). I'm trying to read it from a file and then extract some information. I'd like to get the "times" child and do something with it. I've tried using json.simple and some of the jackson stuff but I keep getting casting/type errors. I'm pretty stuck :/

First I read in the file and it seems to be correctly captured:

JSONParser parser = new JSONParser();
JSONObject data = (JSONObject) parser.parse(new FileReader("test.json"));

I then tried following this: Java JSONObject get children but get errors org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

What I want (think is what I want?) to do is something along the lines create a JSON of the times, and then from there I can make a list of the times/do various operations with them. Or maybe the best approach is to use an ObjectMapper and map it to a matching object?

{
    "id": "ca1b57be-6c38-4976-9050-f9a95a05a38d",
    "name": "some name",
    "results": [
        {
            "name": "https://st-dev.aexp.com/smart-test/v1/test/test",
            "tests": {
                "name": "Body matches string",
                "status": "pass",
                "Response time is less than 200ms": true
            },
            "testPassFailCounts": {
                "Body matches string": {
                    "pass": 100,
                    "fail": 0
                },
                "Response time is less than 200ms": {
                    "pass": 100,
                    "fail": 0
                }
            },
            "times": [
                "48",
                "25",
                "25",
                "28",
                "24",
                "24",
                "35",
                "29",
                "41",
                "28",
                "28",
                "24",
                "31",
                "28",
                "25",
                "27",
                "23",
                "28",
                "44",
                "29",
                "25",
                "23",
                "44",
                "28",
                "22"
            ]
        }
    ]       
}

Thanks much for any help!

Upvotes: 6

Views: 10425

Answers (2)

hubpixel
hubpixel

Reputation: 339

Here is another implementation using library from json.org.

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ProcessJson {
    public void test(String str) throws JSONException {
        JSONObject json = new JSONObject(str);  //initial JSONObject (See explanation section below)
        JSONArray jsonArray = json.getJSONArray("results");  //"results" JSONArray
        JSONObject item = jsonArray.getJSONObject(0);  //first JSONObject inside "results" JSONArray
        JSONArray jsonArrayTimes = item.getJSONArray("times");  //"times" JSONArray

        for (int i = 0; i < jsonArrayTimes.length(); i++) {
            System.out.println(jsonArrayTimes.getInt(i));
        }
    }
}

The dependencies in Maven's pom.xml

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.json/json -->
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20160810</version>
    </dependency>
</dependencies>

The output is:

48
25
25
28
24
24
35
29
41
28
28
24
31
28
25
27
23
28
44
29
25
23
44
28
22

Explanation:

{ } = JSONObject
[ ] = JSONArray

The "times" JSONArray is nested in the first JSONObject of the "results" JSONArray.

Here is the simplified structure:

{ 
    "results": [
        {
            "times": [
                "48",
                "25", ...
            ]

        }
    ]
}

Upvotes: 4

Mick Mnemonic
Mick Mnemonic

Reputation: 7956

There might be a better way of doing this, but using Jackson's ObjectMapper, here's one solution:

String json = readJSON(); // <- read the JSON from somewhere as a plain String
Map<String, Object> jsonDocument = new ObjectMapper()
            .readValue(json, new TypeReference<Map<String, Object>>() {});

List<Object> resultsList = (List<Object>) jsonDocument.get("results");
Map<String, Object> resultsMap = (Map<String, Object>) resultsList.get(0);
List<Integer> times = (List<Integer>) resultsMap.get("times");

// process the times

Basically, your example JSON generalizes only to a Map<String, Object>, which you need to then process element by element, examining the document and adding the corresponding class-casts (Map or List). Jackson converts JSON's name-value pairs (denoted by {}s in the document) as Maps and arrays (denoted by []s) as Lists. The code snippet above assumes that the value of results is always a single-element list.

Upvotes: 0

Related Questions