用springboot用null属性创建对象的JSON



我正在制作一个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 == {" car":{" id":3," name":" car"," Price":13555}}

pojo ==车{id:0,名称:null,价格:null}

上面的JSON对象是字符串Car作为Car的键和值JSON对象,其中JSON对象具有idnameprice Properties

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