0

I have a JSON data like this …

{
{
   "School": "ABC School",
    "School Address": [
{
  "Office": "Road No 123"
},
{
  "Admin Office": "Road No 321"
},
{
  "Admission Office": "Road No 456"
}
],
 "School Brach": [
{
  "Brach name": "North Brach",
  "Brach Id ": "001",
  "Brach Contact": [
    {
      "Primary Phone": "12345676890",
      "AllowExternal":true
    },
    {
      "Primary Email": "xyz@school.com"
      "AllowExternal":true
    },
    {
      "Primary fax": "0123456789",
      "AllowExternal":false
    }
  ]
},
{
  "Brach name": "South Brach",
  "Brach Id ": "002"
},
{
  "Brach name": "West Brach",
  "Brach Id ": "003"
},
{
  "Brach name": "East Brach",
  "Brach Id ": "004"
}
 ]
}

I am getting that JSON from a external call and I have to process that JSON for some element in that JSON.

Like from the above structure suppose I want to get all data for tag “Brach Contact” for “North Brach” where "AllowExternal" is true.

But I do not want to process the complete JSON and do not want to create the model object for the complete JSON structure in my code.

Is there any way I can do that with the JAVA , any external jar or something?

My expected output is JSON structure for "Brach Contact"

"Brach Contact": [
    {
      "Primary Phone": "12345676890",
      "AllowExternal":true
    },
    {
      "Primary Email": "xyz@school.com",
      "AllowExternal":true
    }
  ]

As input source is external , so there is a chance that they may change the JSON structure , so I what something which is independent of structure rather dependent on tag name. Although that is our next priority.

Please note I am using Spring Boot with JAVA 8

Any one help on this…

Biswajit
  • 323
  • 4
  • 15
  • 1
    *"I do not want to process the complete JSON"* You have to, at least up to the point where the data you're looking for is. You can short-circuit at that point and not process the rest. --- *"... do not want to create the model object for the complete JSON structure ..."* Then look for a **streaming** JSON parser. – Andreas May 04 '19 at 06:07
  • 1
    I think you want to look at this one: https://stackoverflow.com/questions/8481380/is-there-a-json-equivalent-of-xquery-xpath – moilejter May 04 '19 at 06:07

1 Answers1

1

You could take a look at JSONPath.

I found a nice introduction article here: https://www.baeldung.com/guide-to-jayway-jsonpath.

However, if you use this, you WILL need to put in the full path to the target element. But this will also parse the whole JSON, without you having to setup models and such.

If you don't want to parse the JSON then I suggest that you take a look at JSON Streaming Parsers.

Jackson has a stream API: https://www.baeldung.com/jackson-streaming-api

Binaek Sarkar
  • 617
  • 8
  • 21