Nikola Toshev
Nikola Toshev

Reputation: 135

Jackson: Deserialize JSON array from JSON object into Java List

I have been stumbled by this for a while. I have a Spring application and would like to parse the following JSON:

{
  "metadata": {...}
  "response": {
    "objects": [
      {
        "name": "someName",
        "properties": [<array_of_properties>]
      },
      ...
    ]
  }
}

into a list of the following Java objects:

public class MyClass {
  String name;
  List<CustomProperties> customProperties;
}

Meaning, I want to extract only the objects array and parse only that. I have tried using a custom deserializer and that works, but I had to do:

@JsonDeserialize(using=MyDeserializer.class)
public class MyClassList extends ArrayList<MyClass>{}

and then:

ObjectMapper objectMapper = new ObjectMapper();
List<MyClass> list = objectMapper.readValue(json, MyClassList.class) 

Is there anyway to avoid extending ArrayList, since currently I am doing that in order to be able to access the .class property.

Upvotes: 0

Views: 1398

Answers (2)

pvpkiran
pvpkiran

Reputation: 27018

You can do something like this. I feel this would be cleaner

@JsonIgnoreProperties(ignoreUnknown = true)
class Wrapper{
  private Response response;
  //setters, getters
}

@JsonIgnoreProperties(ignoreUnknown = true)
class Response{
  private List<MyClass> objects;
  //setters, getters
}

@JsonIgnoreProperties(ignoreUnknown = true)
public class MyClass {
  String name;
  List<CustomProperties> customProperties;
  //setters, getters
}

ObjectMapper objectMapper = new ObjectMapper();
Wrapper wrapper = objectMapper.readValue(json, Wrapper.class) 

You can extrat objects and consequently CustomProperties by traversing the list. You can declare only fields which you are interested in and ignore others by @JsonIgnoreProperties(ignoreUnknown = true)(for example i have not included metadata)

Upvotes: 1

shahaf
shahaf

Reputation: 4973

you can define your json structure with a couple of classes

public class MyJson {
  private MyResponse response;
  ...
}

public class MyResponse {
  private List<MyClass> objects;
  ...
}

public class MyClass {
  String name;
  List<CustomProperty> customProperties;
  ...
}

than you can use Jackson to parse the json string to MyJson class, no special @JsonDeserialize is needed

ObjectMapper objectMapper = new ObjectMapper();
MyJson myJson = objectMapper.readValue(json, MyJson.class);
List<MyClass> list =  myJson.getResponse().getObjects();

Keep in mind, this code is only a draft, all classes should have setters (and getters) and some null checks are required

Upvotes: 1

Related Questions