jackson–更改字段名称

1.概述

更改字段名称以在序列化时映射到另一个JSON属性。

2.更改要序列化的字段名称

创建简单类

public class MyDto {
    
    
    private String stringValue;

    public MyDto() {
    
    
        super();
    }

    public String getStringValue() {
    
    
        return stringValue;
    }

    public void setStringValue(String stringValue) {
    
    
        this.stringValue = stringValue;
    }
}

对其进行序列化将输出以下JSON:

{
    
    "stringValue":"some value"}

要自定义该输出,我们需对getter进行注释 或在属性字段上添加注解 即可:

@JsonProperty("strVal")
public String getStringValue() {
    
    
    return stringValue;
}
/**
   @JsonProperty("strVal")
    private String stringValue;
*/

现在,在序列化中,将获得所需的输出:

{
    
    "strVal":"some value"}
ObjectMapper mapper = new ObjectMapper();
MyDtoFieldNameChanged dtoObject = new MyDtoFieldNameChanged();
dtoObject.setStringValue("a");

String dtoAsString = mapper.writeValueAsString(dtoObject);
System.out.println(dtoAsString);
//{"strVal":"a"}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/niugang0920/article/details/115261813