首页 > 解决方案 > 使用spring-boot向java对象请求Json请求体

问题描述

我有以下 JSON 请求

{
  "FreightCalculationRequest": {
    "Products": [
      {
        "sku": "123",
        "size": "S",
        "quantity": "1",
        "shipAlone": "True",
        "itemType": "Shoe"
      },
      {
        "sku": "123",
        "size": "S",
        "quantity": "1",
        "shipAlone": "True",
        "itemType": "Shoe"
      }
    ],
    "ShipToZip": "54452",
    "IsCommercial": "True"
  }
}

我正在尝试将此请求作为自定义 java 对象发送到 API 控制器方法,然后将相同的对象作为 json 格式的字符串返回。但是,我通过邮递员得到回复,对于产品,shiptoZip 我得到一个空值,对于 isCommercial 我得到假,但我什至没有 false 作为请求中 isCommercial 的值。这是怎么回事?我不知道如何在 Java 中很好地调试,因为我基本上每次都通过键入 mvn spring-boot:start 检查我的应用程序

这是我要返回并用作控制器方法的参数的对象。

public class FreightCalculationRequest {

    private Product[] Products;
    private String ShipToZip;
    private boolean IsCommercial;

    public Product[] getProducts() { return this.Products; }
    public void setProducts(Product[] itemsRequest) { this.Products = itemsRequest; }

    public String getShipToZip() { return this.ShipToZip; }
    public void setShipToZip(String ShipToZip) { this.ShipToZip = ShipToZip; }

    public boolean getIsCommercial() { return this.IsCommercial; }
    public void setIsCommercial(boolean IsCommercial) { this.IsCommercial = IsCommercial; }

}

这是我正在调用的控制器方法

@RequestMapping(value = "/test", produces = MediaType.APPLICATION_JSON_VALUE,  method = RequestMethod.POST)
FreightCalculationRequest TestCall(@RequestBody FreightCalculationRequest calculationRequest) {
    return calculationRequest;

}

为什么我的响应与进来的请求不一样。

更新:我将@JsonProperty 添加到我的变量中,现在响应看起来像这样

{
    "isCommercial": false,
    "shipToZip": null,
    "products": null,
    "Products": null,
    "ShipToZip": null,
    "IsCommercial": false
}

有点失落,也意识到我可以在 mvn 运行时保存我的更改,它会自动编译更改

更新:所以当我最初删除 json 响应中“FreightCalculationRequest”的包装时,我的 json 中的 itemType 实际上抛出了一个错误,所以我认为这是问题所在,但是 itemType 实际上是代码中的一个对象,所以它是由于我没有输入有效属性并彻底阅读 json 解析错误,我有两种解决方案,将响应包装在另一个类中,或者删除 FreightCalculationWrapping。

我还了解到我需要添加 @JsonProperty 来映射 json

谢谢所以

标签: javaspring

解决方案


但是,我通过邮递员得到回复,对于产品,shiptoZip 我得到一个空值,对于 isCommercial 我得到假,但我什至没有 false 作为请求中 isCommercial 的值。这是怎么回事?

您必须将FreightCalculationRequest包装在一个新的模型类中。

创建一个新的Wrapper类,

public class FreightCalculationRequestWrapper {
    @JsonProperty("FreightCalculationRequest")
    private FreightCalculationRequest freightCalculationRequest;

    ...
}

使用这个新的Wrapper类来处理您的请求:

@RequestMapping(value = "/test", produces = MediaType.APPLICATION_JSON_VALUE,  method = RequestMethod.POST)
FreightCalculationResponse TestCall(@RequestBody FreightCalculationRequestWrapper calculationRequest) {
    return calculationRequest;

}

此外,JSON 中的属性名称以大写字母开头。

如果您使用的是 Jackson,那么您可以@JsonProperty(...)在模型字段上使用注释来正确映射它们。

例如:

public class FreightCalculationRequest {
    @JsonProperty("Products")
    private Product[] Products;

    .
    .
    .
}

推荐阅读