How to deserialize JSON response to a complex Java object with nested fields and a map using Jackson?

67 Views Asked by At

I have created an OrderCount class in Java which contains several fields including strings, integers, nested objects, and a map. Here's the structure:

@Data
@SuperBuilder(toBuilder = true)
@NoArgsConstructor
public class OrderCount {
    private String entityId;
    private String entityName;
    private Integer totalTests;
    @Builder.Default
    private Map<String, Integer> products = new HashMap<>();
    private List<OrderCount> childEntities;

    @JsonAnyGetter
    public Map<String, Integer> getProducts() {
        return products;
    }

    @JsonAnySetter
    public void setAdditionalProductProperty(String name, Integer value) {
        products.put(name, value);
    }
}

entityId should map to entityId.

entityName should map to entityName.

totalTests should map to totalTests.

childEntities should map to childEntities.

Remaining fields should map to the products map (Map<String, Integer>).

I expect guidance on how to properly deserialize the JSON response into an OrderCount object using Jackson, ensuring that the fields are mapped correctly as described above. However, if some alternative approaches or libraries could achieve the same result effectively, I welcome suggestions and assistance in exploring those options to find the most suitable solution. Additionally, if this task can be accomplished using any mapper or converter provided by the MapStruct library, I would appreciate guidance on that as well, as I have utilized MapStruct in my project.

The response I'm getting :

{
    "entityId": "01",
    "entityName": "entityName",
    "totalTests": 06,
    "childEntities": [
        {
            "entityId": "01",
            "entityName": "entityName",
            "totalTests": 03,
            "productName1":01,
            "productName2":01,
            .
            .
            .
            "productName_n":01,
        },
        {
            "entityId": "02",
            "entityName": "entityName_2",
            "totalTests": 3,
            "productName1":01,
            "productName2":01,
            .
            .
            .
            "productName_n":01,
            "childEntities": []     
        }
    ],
    "productName1":02,
    "productName2":02,
    .
    .
    .
    "productName_n":02,
}


0

There are 0 best solutions below