Ashley Xu
Ashley Xu

Reputation: 304

How do I access triple nested values in JSON using Java?

I am trying to access the "text" values in the below JSON and create an ArrayList with those values. How would I approach that? I am trying to use com.fasterxml.jackson.

{
    "searchApiFormatVersion": "1.0",
    "searchName": "SalaryAccessRole",
    "description": "",
    "totalRowCount": "2",
    "returnedRowCount": "2",
    "startingReturnedRowNumber": "1",
    "basetype": "Person",
    "columnCount": "1",
    "columnHeaders": [
        {
            "text": "EMPLID",
            "dataType": "string"
        }
    ],
    "resultSet": {
        "rows": [
            {
                "values": [
                    {
                        "text": "2270127",
                        "dataType": "string",
                        "columnHeader": "EMPLID"
                    }
                ]
            },
            {
                "values": [
                    {
                        "text": "1050518",
                        "dataType": "string",
                        "columnHeader": "EMPLID"
                    }
                ]
            }
        ]
    }
}

I've used this to success for the searchName but am trying to get the text under resultSet->rows->values->text.

JsonNode salaryExcludePersonNode = new ObjectMapper().readTree(sourceJson);
String person = salaryExcludePersonNode.get("searchName").textValue();//this works
String person2 = salaryExcludePersonNode.get("resultSet")
                .get("rows")
                .get("values")
                .get("text")
                .textValue());//this says that com.fasterxml.jackson.databind.JsonNode.get(String)  is null

Upvotes: 0

Views: 179

Answers (1)

andrewJames
andrewJames

Reputation: 21910

I know you tagged this question as a Jackson question, but I think JSONPath may be a good fit here.

The JSONPath library is available as a Maven dependency:

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.7.0</version>
</dependency>

For the JSON in your question, all of the "text" values can be selected using a single JSONPath selector:

$.resultSet.rows..text

$ - start at the root of the JSON.

.resultSet.rows - navigate to the rows array.

..text - recursively find all text entries.

The results are automatically added to a Java List:

String jsonAsString = "{...}";
List<String> textList = JsonPath.read(jsonAsString, "$.resultSet.rows..text");

You can also read from a java.io.File directly:

File jsonFile = "/your/path/to/file.json";
List<String> textList = JsonPath.read(jsonFile, "$.resultSet.rows..text");

The list will be populated with 2 entries:

2270127
1050518

References:

JSONPath syntax overview

JavaDocs

Upvotes: 1

Related Questions