JackSon中对象大小写的问题
今天在使用Jackson将json转化为javabean时,因为大小写而出现了一点问题。
javabean
public class TemperatureData { private String humidity; private String temperature; private String PM; public String getHumidity() { return humidity; } public void setHumidity(String humidity) { this.humidity = humidity; } public String getTemperature() { return temperature; } public void setTemperature(String temperature) { this.temperature = temperature; } public String getPM() { return PM; } public void setPM(String PM) { this.PM = PM; } }
解析时,上述的PM字段始终无法解析。
查阅文档:
How Jackson ObjectMapper Matches JSON Fields to Java Fields To read Java objects from JSON with Jackson properly, it is important to know how Jackson maps the fields of a JSON object to the fields of a Java object,
so I will explain how Jackson does that. By default Jackson maps the fields of a JSON object to fields in a Java object by matching the names of the JSON field to the getter and setter methods in the Java object.
Jackson removes the "get" and "set" part of the names of the getter and setter methods, and converts the first character of the remaining name to lowercase. For instance, the JSON field named brand matches the Java getter and setter methods called getBrand() and setBrand().
The JSON field named engineNumber would match the getter and setter named getEngineNumber() and setEngineNumber(). If you need to match JSON object fields to Java object fields in a different way,
you need to either use a custom serializer and deserializer, or use some of the many Jackson Annotations.
可以看出,原因是,如果字段是private属性,jackson会直接根据get、set函数的命名来决定字段的命名。
可以发现,不管是PM,还是pM,他们的set方法统一是setPm(),jackson只能按照java的规范,默认开头字母小写,所以才会出现上述问题。
解决方案:
直接加上注解,告诉Jackson所有的字段都可以直接按照字段名识别,不管是不是private。
@JsonAutoDetect(fieldVisibility= JsonAutoDetect.Visibility.ANY,getterVisibility= JsonAutoDetect.Visibility.NONE) public class TemperatureData {
再次测试,就可以正常解析了。