0

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
4
  • There is, if you use more advanced methods of parsing. For example: javahai.blogspot.com/2016/03/… Commented Nov 1, 2019 at 11:33
  • You can also go with the answers from this question. Commented Nov 1, 2019 at 11:34
  • What json library do you use? Jackson, gson, etc? Commented Nov 1, 2019 at 11:42
  • Hope this can help: baeldung.com/guide-to-jayway-jsonpath Commented Nov 1, 2019 at 11:46

6 Answers 6

3

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

An example to help understand better.

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

1

Try JsonNode by below step

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

1 Comment

or you can directly write below code String imageId = jsonNode.findPath ("images").get (0).findPath ("imageID").asText ();
0

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..

Comments

0

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

Comments

-2

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");

1 Comment

"... but surely there must be an easier way" can you explain what makes things easier here comparing to code from question?

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.