如何将属性序列化为json对象?

时间:2018-10-16 18:28:46

标签: json spring-boot serialization jackson2

如何使用杰克逊序列化以下通用响应?

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
}

预期输出:

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

我怎么能用杰克逊得到这个??

如果我将wrap_root_value设置为true,那么它将以以下格式进行序列化。...

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

1 个答案:

答案 0 :(得分:0)

我可以通过使用@JsonTypeInfo@JsonTypeName批注来实现这一点。

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;
}