Search code examples
jsonspring-bootserializationjackson2

How can I serialize properties as json object?


How can I serialize following generic response using jackson??

public class GenericResponse{
    private String resource;
    private Integer status;
    private ErrorInfo response;
    //setters and getters
}

public class ErrorInfo {
    private String errorCode;
    private String errorDetails;
    @JsonUnwrapped
    private ErrorFactory errorFactory;
    //setters and getters
}

expected output:

{
    "resource": "xxxxxx",
    "status": xxxxx,
    "response": {
        "error-info": {
            "errorCode": "xxxxxx",
            "errorDetails": "xxxxx"
            }
    }
}

How can i get this using jackson???

If i set wrap_root_value to true then it is serializing in below format....

{
    "GenericResponse": {
        "resource": "xxxxxx",
        "status": xxxxxxxxx,
        "response": {
            "errorCode": "xxxxxxxxx",
            "errorDetails": "xxxxxxxxxxx"
        }
    }
}

Solution

  • I am able to get this by using @JsonTypeInfo and @JsonTypeName annotations.

    public class GenericResponse{
    private String resource;
    private Integer status;
    @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
    private ErrorInfo response;
    //setters and getters
    }
    
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonTypeName("error-info")
    public class ErrorInfo {
    private String errorCode;
    private String errorDetails;
    @JsonUnwrapped
    private ErrorFactory errorFactory;
    }