spring boot反序列化json时如何忽略不需要的属性

遇到一个奇怪的问题纠结了好几天,最终发现是反序列化json的时候需要忽略部分参数。
前端put更新请求的时候,出现错误,chrome调试错误代码如下:

{"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"}

这几天一直纠结于这个问题,今晚突然醒悟应该是在反序列化的时候,忽略掉customer对象。
请教大神,应该如何操作?

阅读 7.4k
2 个回答

当一个对象不够的时候,就再创建一个对象。

假设你的类是这个样子:

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

那你反序列化的时候就不应该再用这个类,而应该弄一个新类:

public class FooUpdateCmd {
   ...
}

然后你代码里自己决定怎么使用FooUpdateCmd。

在对象mold的定义中,getCustomer方法前面加上JsonIgnore,使其在解析json的时候忽略掉,这个错误就可以解决了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题