相信大家都有过,使用fastjson把java对象转换成json字符串,而对象里面大写开关的属性被转换成了小写。现在就在这里说下我用到的方法:
首先来个错误的示范,一般大写的属性都会这样定义:
@JSONField(name = "RequestMsg")
private RequestMsgEntity RequestMsg;
public RequestMsgEntity getRequestMsg() {
return RequestMsg;
}
public void setRequestMsg(RequestMsgEntity requestMsg) {
RequestMsg = requestMsg;
}
这样定义的属性,通过注解是找不到的,原因如下:
下面是里面一段的源码
String propertyName = ((2)) + (3);
Field field = (clazz, propertyName);
if (field != null) {
JSONField fieldAnnotation = ();
if (fieldAnnotation != null && ().length() != 0) {
propertyName = ();
if (aliasMap != null) {
propertyName = (propertyName);
if (propertyName == null) {
continue;
}
}
}
}
可以看到它在找field的时候是通过methodName来找的,而这里对首字母做了小写的处理,而我们定义的属性首字母是大写的导致这个注解找不到。
所以解决办法就是:
@JSONField(name = "RequestMsg")
private RequestMsgEntity requestMsg;
public RequestMsgEntity getRequestMsg() {
return requestMsg;
}
public void setRequestMsg(RequestMsgEntity requestMsg) {
= requestMsg;
}
我们将属性名称的首字母改成小写,这样就能找到注解,然后转换成json的时候就正确了。
就写这么多,希望能帮到大家!