面对不遵守驼峰命名规则的接口咋办?当然首先要吐槽一下,不过接口是别人定的,虽然看着不爽但还是得去适配,比如cardNumber,他返回的叫{CARDNUMBER:''}。
通过对API的研究可以通过@JsonProperty以及@JsonAutoDetect来实现。
先看代码
@JsonAutoDetect(JsonMethod.FIELD)
public class MemberApiParameter implements Serializable {
private static final long serialVersionUID = 1L;
/** 姓名 **/
@JsonProperty("NAME")
private String name;
/** 性别 **/
@JsonProperty("SEX")
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
@JsonProperty("NAME")顾名思义,就是显示指定字段的别名,不管是输入还是输出都是这个名字。
@JsonAutoDetect(JsonMethod.FIELD)这个的意思是指解析字段,如果不这样设置,有兴趣的朋友可以试一下,会输出两套东西,类似{name:'',NAME:''},也就是说字段和getter方法都解析了,所以需要制定只解析字段名,忽略方法。还有一种方法就是需要一行行的在所有getter上加上@JsonIgnore,如果字段多就累死了。
JsonMethod的API说明:
Enum Constant Summary
This pseudo-type indicates that all of real types are included |
Creators are constructors and (static) factory methods used to construct POJO instances for deserialization |
Field refers to fields of regular Java objects. |
Getters are methods used to get a POJO field value for serialization, or, under certain conditions also for de-serialization. |
"Is getters" are getter-like methods that are named "isXxx" (instead of "getXxx" for getters) and return boolean value (either primitive, or |
This pseudo-type indicates that none of real types is included |
Setters are methods used to set a POJO value for deserialization. |
如果有更好的更加通用的办法欢迎留言补充。
转自:http://www.tuicool.com/articles/aaqMfa7