-2

I have a huge JSON but I only need to parse specific fields. I know paths to these fields so I decided to try JPath and it works but I want to parse all fields at once. Let's say I have such JSON:

{
  "data": [
    {
      "field1": 1,
      "field2": 1,
      ...
      "another_data": [ {
        "required_field1": "1",
        "required_field2": "2"
      }
      ],
      ...
    }
  ]
}

I want to get only required fields with these paths and map it to Java POJO:

$.data[*].another_data[*].required_field1
$.data[*].another_data[*].required_field2

So as a final result I want to have a list of Java objects, where the object contains required_field1 and required_field2.

UPD:

  • how it works now

I have a Java POJO that's a container

class RequiredInfo {

private String field1;
private String field2;

//constructor, setters, etc

}

I read JSON path 2 times by using JPath:

String json = "...";

Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);

List<String> reqFields1 = JsonPath.read(document, "$.data[*].another_data[*].required_field1");
List<String> reqFields2 = JsonPath.read(document, "$.data[*].another_data[*].required_field2")

and then I map it to my POJO

  for (int i = 0; i < reqFields1.size(); i++) {
      res.add(new RequiredInfo(reqFields1.get(i), reqFields2.get(i)));
   }

bit I think there is a better way how I can do it

user23
  • 21
  • 6
  • 1
    `I want to get only required fields with these paths and map it to Java POJO` > why? Why does it have to be a pojo, and can't be a JSON object with key-value pairs, or any other form of container that holds this information? – TreffnonX Mar 23 '21 at 12:51
  • Perhaps this tutorial will help: https://www.baeldung.com/jackson-serialize-field-custom-criteria. There are other options, for flattening Json structures (look around the Baedung jackson tutorias) Also as @TreffnonX you can always deserialise to a Map etc. – Gavin Mar 23 '21 at 12:55
  • @TreffnonX I think it may be a different structure, I just wanted to say that these fields are related, so I wanted to make sure that they'll be in same "container" – user23 Mar 23 '21 at 13:10

1 Answers1

1

You can try by creating a JSON object and get data:

JSONObject yourJsonObject = (JSONObject) new JSONParser().parse(yourJson);
JSONObject data = (JSONObject) yourJsonObject.get("data");
JSONObject data0 = (JSONObject) data.get(0);
JSONObject another_data = (JSONObject) data0.get("another_data");

String required_field1 = another_data.get("required_field1").toString();
String required_field2 = another_data.get("required_field2").toString();


Now that you have values, you can add them in your POJOs.