Matt
Matt

Reputation: 1043

In Java how to easily get the value of a nested key from a JSON String / Object

I am using Java. I have a string that I have converted to a JSON Object. I want to extract the value of one of the Keys. At the moment I am using this code:

String imageId = myJsonObject.getJSONObject("meta")
                             .getJSONObject("verification")
                             .getJSONObject("derivedData")
                             .getJSONArray("images")
                             .getJSONObject(0)
                             .getString("imageID");

This code works but surely there must be an easier way. In javascript I could access the value simply by writing this:

myJsonObject.meta.verification.derivedData.images[0].imageId

Upvotes: 0

Views: 688

Answers (6)

Mohammad Zeryab Khan
Mohammad Zeryab Khan

Reputation: 16

I have created a small class for this purpose which can basically get value from json using a path only used google.gson

https://github.com/izeryab/JsonParser

Here is how to use this for getting nested value from json:

public class Main {
    public static void main(String[] args) {

        String json = "{\"data\":[{\"stuff\":[\n" + "    {    \"onetype\":[\n"
                + "        {\"id\":1,\"name\":\"John Doe\"},\n" + "        {\"id\":2,\"name\":\"Don Joeh\"}\n"
                + "    ]},\n" + "    {\"othertype\":[\n" + "        {\"id\":2,\"company\":\"ACME\"}\n" + "    ]}]\n"
                + "},{\"otherstuff\":[\n" + "    {\"thing\":\n" + "        [[1,42],[2,2]]\n" + "    }]\n" + "}]}";

        String name = JsonUtil.getJsonElementFromJsonStringUsingPath("data>0>stuff>0>onetype>0>name", json, ">").getAsString();
        int id= JsonUtil.getJsonElementFromJsonStringUsingPath("data>0>stuff>0>onetype>0>id",json,">").getAsInt();
        
        System.out.println("id : "+id);
        System.out.println("name : "+name);
    }

}

Corresponding JAVA DOCS: https://izeryab.github.io/JsonParser/JsonUtil.html

Upvotes: 0

sourabh.gangoli
sourabh.gangoli

Reputation: 73

Try JsonNode by below step

 String imageId= jsonNode.
 findPath("meta")
.findPath("verification")
.findPath("derivedData")
.findPath("images")
.get (0).findPath ("imageID").asText ();

Upvotes: 1

Kelvin
Kelvin

Reputation: 376

You may need to install library such as JsonPath to help you select values from a JSON object

An example to help understand better.

Upvotes: 3

Jack Griffiths
Jack Griffiths

Reputation: 1

You can use GSon, I've used it before (see below)

// Convert to a JSON object to print data
    JsonParser jp = new JsonParser(); //from gson
    JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
    JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object.

    JsonArray jsonDataArray = rootobj.getAsJsonArray("data");
    JsonPrimitive totalJson = rootobj.getAsJsonPrimitive("total");
    JsonPrimitive nextJson = rootobj.getAsJsonPrimitive("next");

Upvotes: -2

Rifaquat Siddiqui
Rifaquat Siddiqui

Reputation: 77

You can use external library Gson

 Gson gson=new Gson();
/*You can convert to your DTO as well */
 Map<Object,Object> map = gson.from(myJsonObject,Map.class);

Other way is using objectmapper example of fasterxml.

ObjectMapper objectMapper=new ObjectMapper();
    /*You can convert to your DTO as well */
objectMapper.readValue(data, Map.class);

Upvotes: 1

Gro
Gro

Reputation: 1683

You need to use the 'Java API for JSON Binding' JSON-B instead of JSON-P. Using JSON-B you can serialize and deserialize between Java objects and data streams and access values of objects POJO style (similar to what you expect).

API details can be found here

A quick start tutorial can be found here and at many website only google search away..

Upvotes: 0

Related Questions