【问题标题】:How can I serialize properties as json object?如何将属性序列化为 json 对象?
【发布时间】:2019-03-21 08:44:49
【问题描述】:

如何使用 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
}

预期输出:

{
    "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"
        }
    }
}

【问题讨论】:

  • 你提到它会在 wrap_root_value 为真时执行此操作,如果为假会发生什么情况?
  • 您的预期输出是无效的 JSON。为什么需要这种形式?
  • @Zergled 默认情况下该属性为假。 {“资源”:“xxxxxx”,“状态”:xxxxx,“响应”:{“errorCode”:“xxxxxx”,“errorDetails”:“xxxxx”}}
  • @Selindek Soory 这是一个错字

标签: json spring-boot serialization jackson2


【解决方案1】:

我可以通过使用 @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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    • 2012-03-01
    • 2015-07-29
    • 1970-01-01
    相关资源
    最近更新 更多