使用Jackson解析首字母大写的json字符串

时间:2021-05-13 15:27:40

Jackson在解析返回的json字符串时始终报错,纠结很久之后才找到原因,原来是是由于json字符串中的字母都是首字母大写,导致jackson找不到相应的KEY。

在项目中经常使用从服务器获取的数据,有时从服务器获取的json字符串中的首字母是大写的,使用Jackson解析是就会报一下错误:

Exception in thread "main" org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "XXX" (Class xxxx), not marked as ignorable .

异常信息告诉说XXX属性字段在类型xxx中没有找到,也没有标记为忽略。

但是在你的bean中确实存在这个字段,而只不过是这个字段的首字母是大写而已。

解决这个问题只需要在属性字段上面加上@JsonProperty();即可。

 public class CommissionItemVo implements Serializable{

     /**
*
*/
private static final long serialVersionUID = 1L; private int docId;
@JsonProperty("CName")
private String CName;
@JsonProperty("CPhone")
private String CPhone;
@JsonProperty("BlockName")
private String BlockName;
@JsonProperty("SeeTime")
private String SeeTime;
@JsonProperty("Cost")
private String Cost;
@JsonProperty("EndSettleTime")
private String EndSettleTime; public int getDocId() {
return docId;
} public void setDocId(int docId) {
this.docId = docId;
} public String getCName() {
return CName;
} public void setCName(String cName) {
CName = cName;
} public String getCPhone() {
return CPhone;
} public void setCPhone(String cPhone) {
CPhone = cPhone;
} public String getBlockName() {
return BlockName;
} public void setBlockName(String blockName) {
BlockName = blockName;
} public String getSeeTime() {
return SeeTime;
} public void setSeeTime(String seeTime) {
SeeTime = seeTime;
} public String getCost() {
return Cost;
} public void setCost(String cost) {
Cost = cost;
} public String getEndSettleTime() {
return EndSettleTime;
} public void setEndSettleTime(String endSettleTime) {
EndSettleTime = endSettleTime;
} public static long getSerialversionuid() {
return serialVersionUID;
} @Override
public String toString() {
return "CommissionItemVo [docId=" + docId + ", CName=" + CName + ", CPhone=" + CPhone + ", BlockName=" + BlockName + ", SeeTime=" + SeeTime + ", Cost=" + Cost + ", EndSettleTime=" + EndSettleTime + "]";
} }