簡體   English   中英

使用springboot創建具有空屬性的對象的Json到POJO

[英]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對象具有idnameprice屬性

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM