1

I need to get codec value from jsonnode using java. The following is the jsonnode with parent and child nodes.

{  
   "DetectedProperties":{  
      "Bitrate":262610704,
      "FrameRate":"24/1",
      "FileSize":32827252,
      "Height":1080,
      "Width":1920,
      "DurationMillis":1.0,
      "codec":"prores"
   }
}

the the following code snipet doesn't return a value for codec. It always returns null.

JsonNode videoProperties = getCodecInfo(videoFile);
JsonNode videoInfo = videoProperties.get("DetectedProperties");
log.debug("codec: " + videoInfo.get("codec").toString()); // returns null

How to get the codec value from the above json using java?

Kindly provide your inputs.

SST
  • 2,054
  • 5
  • 35
  • 65
  • try to make a model class of your json array and get the value of element using that model class – sourabh kaushik Aug 20 '18 at 06:28
  • try `videoInfo.get("codec").asText()` – Rajen Raiyarela Aug 20 '18 at 06:38
  • @RajenRaiyarela getting java.lang.NullPointerException while trying your code – SST Aug 20 '18 at 06:50
  • which Jackson version are you using? – Rajen Raiyarela Aug 20 '18 at 06:53
  • Your code works. I am getting "prores" as a result. Could you check the code in getCodecInfo() whether it returns the json tree properly or not? – S.K. Aug 20 '18 at 07:26
  • @S.K. Its not working for me.. :( – SST Aug 20 '18 at 07:28
  • Can you try to print "videoProperties" and post the result here? If it is not fetching the tree properly, you can post the code to create the json tree here. – S.K. Aug 20 '18 at 07:30
  • log.debug("BBBBBBBBBBBBBBBBB: " + videoProperties.get("DetectedProperties")); Result: BBBBBBBBBBBBBBBBB: {"Bitrate":262610704,"FrameRate":"24/1","FileSize":32827252,"Height":1080,"Width":1920,"DurationMillis":1.0,"codec":"prores"} – SST Aug 20 '18 at 07:32
  • This seems right. what is the output of next statement: videoInfo.get("codec") ? also can you try using asText() instead of toString()? – S.K. Aug 20 '18 at 07:56
  • both getting NullPointerException :( – SST Aug 20 '18 at 08:07
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/178329/discussion-between-s-k-and-sst). – S.K. Aug 20 '18 at 08:44

1 Answers1

1

You can use json expression "/DetectedProperties/codec" for this.

  JsonParser parser = new JsonFactory().createParser(getCodecInfo().toString());
  parser.setCodec(new ObjectMapper());
  TreeNode tree = parser.readValueAsTree();
  System.out.println(tree.at("/DetectedProperties/codec"));
S.K.
  • 3,597
  • 2
  • 16
  • 31