1.背景
在将一个对象转成ArrayNode时,出现了下面的情况
ParamVo(name=Date, value=20202020, desc=ddddddddddd, isEncryption=true)
public class ParamVo implements Serializable {
private static final long serialVersionUID = 1L;
/**
*参数名称
*/
private String name;
/**
* 参数值
*/
private String value;
/**
* 参数描述
*/
private String desc;
/**
* 是否加密
*/
private boolean isEncryption;
}
输出的结果为
public static void main(String[] args) throws Exception {
ParamVo paramVo = new ParamVo("Date", "$dateDay", "dddddddd", true);
ObjectMapper OBJECT_MAPPER = new ObjectMapper();
System.out.println(OBJECT_MAPPER.writeValueAsString(paramVo));
}
# {"name":"Date","value":"$dateDay","encryption":true,"desc":"dddddddd"}
很明显 isEncryption 变成了 encryption,这是什么原因呢?(自行查找原因)
但是如何解决这个问题呢?
首先JackSon 根据getter 来定位Json 对象的属性,而不是字段,现在我们给字段增加注解
@JsonProperty
public class ParamVo implements Serializable {
private static final long serialVersionUID = 1L;
/**
*参数名称
*/
private String name;
/**
* 参数值
*/
private String value;
/**
* 参数描述
*/
@JsonProperty("kkk")
private String desc;
/**
* 是否加密
*/
@JsonProperty("isEncryption")
private boolean isEncryption;
}
现在输出结果(isEncryption不再变成encryption,desc变成了kkk)
public static void main(String[] args) throws Exception {
ParamVo paramVo = new ParamVo("Date", "$dateDay", "dddddddd", true);
ObjectMapper OBJECT_MAPPER = new ObjectMapper();
System.out.println(OBJECT_MAPPER.writeValueAsString(paramVo));
}
#{"name":"Date","value":"$dateDay","kkk":"dddddddd","isEncryption":true}