简体   繁体   English

对于非字符串类型的字段,Spring Boot 无法从 POST 请求将 JSON 转换为 pojo

[英]Spring Boot Failed to Convert JSON to pojo from POST request for fields that are not of type string

 public class Dog {
   private String name;
   private int weight;
     //...getters and
    //setters and constructor 
 }

Controller:控制器:

 @RequestMapping(value = "/dogs", method = RequestMethod.POST, 
 produces = "application/json")
 public void createDog(Dog dog) {
    dr.save(dog); 
 }

How come when I call the endpoint with json {"name":"bark", "weight":50} I get an error:当我使用 json {"name":"bark", "weight":50}调用端点时,为什么会出现错误:

Failed to convert value of type 'null' to required type 'int';无法将“null”类型的值转换为所需的“int”类型; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [null] to type [int] for value 'null';嵌套异常是 org.springframework.core.convert.ConversionFailedException:无法从类型 [null] 转换为值 'null' 的类型 [int]; nested exception is java.lang.IllegalArgumentException: A null value cannot be assigned to a primitive type", "objectName": "dog", "field": "weight", "rejectedValue": null, "bindingFailure": true, "code": "typeMismatch"嵌套异常是 java.lang.IllegalArgumentException: A null 值不能分配给原始类型", "objectName": "dog", "field": "weight", "rejectedValue": null, "bindingFailure": true, "代码": "类型不匹配"

"message": "Validation failed for object='dog'. Error count: 1 "message": "object='dog' 验证失败。错误计数:1

edit: I get the same issue with booleans and doubles.编辑:我对布尔值和双打也有同样的问题。 I guess I have to use objects not primitives?我想我必须使用对象而不是基元?

在你的create方法中将注解@RequestBody添加到 param dog

Need to specify the @RequestBody annotation to specify we are sending DOG object as part of request body:需要指定@RequestBody注释来指定我们将 DOG 对象作为请求正文的一部分发送:

@RequestMapping(value = "/dogs", method = RequestMethod.POST, produces = "application/json") 
public void createDog((**@RequestBody** Dog dog) { dr.save(dog); }

仅适用于对象,因此请使用 Integer 而不是 int。

If exist possibility object receive null, you can't use type primitives, same int, char, boolean.如果存在可能性对象接收空值,则不能使用类型原语,相同的 int、char、boolean。

private int weight

Use type objects same Integer, Boolean ... for one type primitive has a Object, then can receive null value.使用类型对象相同的 Integer, Boolean ... 对于一个类型原语有一个对象,则可以接收空值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM