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 {

再次測試,就可以正常解析了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM