Search code examples
jsonspringspring-bootspring-restcontroller

Spring Rest: Mapping a property of a bean as nested JSON


My Spring REST controller needs to map an object parameter that looks like this:

{
    "batchId": 43091,
    "domain": "XX",
    "code": "XXX",
    "effectiveDate": "2020-02-13",
    "status": "Y",
    "result": [{"ruleName":"name",...]}]
}

I'm having trouble coming up with the DTO to convert this data into. What I have so far looks like this:

@Data
@NoArgsConstructor
@EqualsAndHashCode
public class ValidationResult {
    private String result;
    private String status;
    private String batchId;
    private String domain;
    private String code;
    private String effectiveDate;
}

But result, which contains the embedded JSON, is always null. I don't care about that JSON being mapped, as I'm storing it as a JSON type in the database (Postgresql). But what Java type do I need to declare it to be to get the controller to convert it? I tried making it a javax.json.JsonObject, but that failed.


Solution

  • What we always do with those json inputs is to map those to specific classes. Which means, in your case, result could be a class which itself contains the given fields "ruleName" and their types. Then your Validaton Result containts a private Result result. If naming conventions are quite right the used mapper will be able to convert and map the response to the class and its properties.