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
Pshemo
  • 118,400
  • 24
  • 176
  • 257
Matt
  • 523
  • 5
  • 21

5 Answers5

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.

Kelvin Ho
  • 328
  • 2
  • 3
  • 12
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);
1

Try JsonNode by below step

 String imageId= jsonNode.
 findPath("meta")
.findPath("verification")
.findPath("derivedData")
.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..

Gro
  • 1,472
  • 1
  • 10
  • 18
-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");
  • "*... but surely there must be an easier way*" can you explain what makes things easier here comparing to code from question? – Pshemo Nov 01 '19 at 12:02