[英]Json to POJO with springboot creating object with null attributes
我正在制作AngularJs + SpringBoot CRUD应用程序。 我可以在控制器上正确检索Json,但是当我转换为pojo时,它将获得null属性。
关于变量名拼写错误的大多数类似问题。我已经多次编写了该类并对其进行了修订。 仍然无法正常工作。
模型:
private static final long serialVersionUID = 1L;
@Id
@SerializedName("id")
private int id;
@SerializedName("name")
private String name;
@SerializedName("price")
private Long price;
public Car() {
}
public Car(int id, String name, Long price) {
super();
this.id = id;
this.name = name;
this.price = price;
}
// getters / setters
控制器:
@RequestMapping(value = "add", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity add(@RequestBody String jsonCar ) throws Exception {
Car car = new Gson().fromJson(jsonCar, Car.class);
// repository.save(car);
System.out.println("Json== " + jsonCar);
System.out.println("pojo==" + car);
return new ResponseEntity<>(HttpStatus.CREATED);
}
测试输出:
Json == {“汽车”:{“ id”:3,“名称”:“汽车”,“价格”:13555}}
pojo ==汽车{id:0,名称:空,价格:空}
上面的JSON对象以String Car
作为键,并且是Car
类型的JSON对象的值,其中JSON对象具有id
, name
和price
属性
{
"id":3,
"name":"car",
"price":13555
}
因此,您需要持有Car
对象的外部类
public class CarResponse {
@SerializedName("Car")
private Car car;
// getters and setters
}
然后将字符串jsonCar
转换为CarResponse
CarResponse car = new Gson().fromJson(jsonCar, CarResponse.class);
car.getCar() //get the Car object now
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.