java 对象大小写_JackSon中对象大小写的问题

今天在使用Jackson将json转化为javabean时,因为大小写而出现了一点问题。

javabean

public classTemperatureData {privateString humidity;privateString temperature;privateString PM;publicString getHumidity() {returnhumidity;

}public voidsetHumidity(String humidity) {this.humidity =humidity;

}publicString getTemperature() {returntemperature;

}public voidsetTemperature(String temperature) {this.temperature =temperature;

}publicString getPM() {returnPM;

}public voidsetPM(String PM) {this.PM =PM;

}}

解析时,上述的PM字段始终无法解析。

查阅文档:

How Jackson ObjectMapper Matches JSON Fields to Java Fields

To read Java objectsfrom 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.

Bydefault 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 JSONobject 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 {

再次测试,就可以正常解析了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值