Christopher
Christopher

Reputation: 153

Jackson - How to deserialize list of child objects that contain an extra wrapper

Problem: Im struggling to map the child objects (items) to the Product.java class because of the extra wrapper.

Json:

{
"id": "1",
"desc": "Shopping",
"items": [
  {
    "product": {
      "id": 2,
      "name": "Sugar"
    }
  },
  {
    "product": {
      "id": 1,
      "name": "Flour"
    }
  }
]

}

Domain Model - Order(JSON Parent):

public class Order {

private int id;

private String desc;

private Set<Product> items; 

}

Domain Model - Product(JSON Child)

public class Product {

private int id;

private String name;

}

How do i use jackson or any other json dependency to map this json string to these domain models ?

Upvotes: 1

Views: 1235

Answers (2)

Christopher
Christopher

Reputation: 153

Here is another solution that I managed to find using Jackson's dependency for those who arent using Gson.

In Order.java class:

public class Order {

private int id;

private String desc;

private Set<Product> items; 

private static final ObjectMapper objectMapper = new ObjectMapper();

@JsonProperty("items")
    public void setItems(List<Map<String, Object>> items) {
        for(Map<String, Object> map: items) {
            Product product = objectMapper.convertValue(map.get("product"), Product.class);
            this.addItem(product);
        }
    }

}

Upvotes: 1

Gibbs
Gibbs

Reputation: 22956

String data = "{" + 
                "\"id\": \"1\"," + 
                "\"desc\": \"Shopping\"," + 
                "\"items\": [" + 
                "  {" + 
                "    \"product\": {" + 
                "      \"id\": 2," + 
                "      \"name\": \"Sugar\"" + 
                "    }" + 
                "  }," + 
                "  {" + 
                "    \"product\": {" + 
                "      \"id\": 1," + 
                "      \"name\": \"Flour\"" + 
                "    }" + 
                "  }" + 
                "]" + 
                "}";
        
        Gson gson = new Gson();
        Order o = gson.fromJson(data, Order.class);
        System.out.println(o);

The line does the trick is

Order o = gson.fromJson(data, Order.class);

Upvotes: 2

Related Questions