在jackson中反序列化时,在json对象中添加父变量



我想在jackson中的反序列化过程中在和jsonobject中添加扩展类变量。

ParentResponse类:

@JsonInclude(value = Include.NON_EMPTY)
public class ParentResponse extends DefaultResponse {
@JsonProperty("parentname")
private String parentName;
// Getter and setter
}

默认响应类别:

@JsonInclude(value = Include.NON_EMPTY)
public class DefaultResponse{
@JsonProperty("status")
private String status;
// Getter and Setter

@JsonProperty("responseInfo")
public JSONObject responseInfo() {
JSONObject jsonResponse = new JSONObject();
jsonResponse.put("status", this.status);
return new JSONObject();
}
}
public class ResponseResource {
public static void main(String[] args) {
ParentResponse response = new ParentResponse();
response.setStatus("success");
System.out.println(new ObjectMapper().writer().withDefaultPrettyPrinter().writeValueAsString(response));
}
}

这将返回

{
"status": "success",
}

我的要求是

{
"responseInfo" : {
"status" : "success"
}

如果没有杰克逊的customSerizer,这可能吗?

您可以声明一个返回单个条目Map的方法,该方法将用作getter,而不是方法responseInfo()

注意 此方法不需要任何数据绑定注释,只需要将其命名为常规getter,即可被Jackson视为getter。

为了避免在序列化DefaultResponse时将"status"属性复制为属性"responseInfo"的一部分和status字段的表示,可以使用

  • 通过不公开getter来阻止Jackson访问它(这可能不方便,因为您可能需要getter(
  • 另一种方法是用@JsonIgnore对字段进行注释,这将导致在序列化去序列化
  • 最灵活的解决方案是使用@JsonProperty注释的access属性,因为它提供了更多的控制。例如,如果将access属性分配给JsonProperty.Access.WRITE_ONLY,则在反序列化JSON时会将其考虑在内,但在序列化过程中会将其排除在外

这就是它的实现方式:

@JsonInclude(value = JsonInclude.Include.NON_EMPTY)
@Setter
@Getter
public static class DefaultResponse {
@JsonProperty(value = "status", access = JsonProperty.Access.WRITE_ONLY)
private String status;

public Map<String, String> getResponseInfo() {
return Map.of("status", status);
}
}

用法示例:

public static void main(String[] args) throws JsonProcessingException {
ParentResponse response = new ParentResponse();
response.setStatus("success");

String jsonResponse = new ObjectMapper().writer()
.withDefaultPrettyPrinter()
.writeValueAsString(response);

System.out.println(jsonResponse);
}

输出:

{
"responseInfo" : {
"status" : "success"
}
}

最新更新