鍍金池/ 問答/Java  網(wǎng)絡(luò)安全/ spring boot反序列化json時(shí)如何忽略不需要的屬性

spring boot反序列化json時(shí)如何忽略不需要的屬性

遇到一個(gè)奇怪的問題糾結(jié)了好幾天,最終發(fā)現(xiàn)是反序列化json的時(shí)候需要忽略部分參數(shù)。
前端put更新請(qǐng)求的時(shí)候,出現(xiàn)錯(cuò)誤,chrome調(diào)試錯(cuò)誤代碼如下:

{"timestamp":1532181308556,"status":400,"error":"Bad Request","exception":"org.springframework.validation.BindException","errors":[{"codes":["typeMismatch.mold.customer","typeMismatch.customer","typeMismatch.org.sipes.entity.Customer","typeMismatch"],"arguments":[{"codes":["mold.customer","customer"],"arguments":null,"defaultMessage":"customer","code":"customer"}],"defaultMessage":"Failed to convert property value of type 'java.lang.String' to required type 'org.sipes.entity.Customer' for property 'customer'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'org.sipes.entity.Customer' for property 'customer': no matching editors or conversion strategy found","objectName":"mold","field":"customer","rejectedValue":"[object Object]","bindingFailure":true,"code":"typeMismatch"}],"message":"Validation failed for object='mold'. Error count: 1","path":"/mold/mold"}

這幾天一直糾結(jié)于這個(gè)問題,今晚突然醒悟應(yīng)該是在反序列化的時(shí)候,忽略掉customer對(duì)象。
請(qǐng)教大神,應(yīng)該如何操作?

回答
編輯回答
選擇

在對(duì)象mold的定義中,getCustomer方法前面加上JsonIgnore,使其在解析json的時(shí)候忽略掉,這個(gè)錯(cuò)誤就可以解決了。

2017年3月3日 06:05
編輯回答
哚蕾咪

當(dāng)一個(gè)對(duì)象不夠的時(shí)候,就再創(chuàng)建一個(gè)對(duì)象。

假設(shè)你的類是這個(gè)樣子:

public class Foo {
   private Customer customer;
   ...
}

那你反序列化的時(shí)候就不應(yīng)該再用這個(gè)類,而應(yīng)該弄一個(gè)新類:

public class FooUpdateCmd {
   ...
}

然后你代碼里自己決定怎么使用FooUpdateCmd。

2018年1月31日 07:09