【问题标题】:Post a JSON Array into Spring Boot RestController将 JSON 数组发布到 Spring Boot RestController
【发布时间】:2017-10-15 07:44:39
【问题描述】:

我正在发布这样的内容:

{
  "stuff": [
    {
      "thingId": 1,
      "thingNumber": "abc",
      "countryCode": "ZA"
    },
    {
      "thingId": 2,
      "thingNumber": "xyz",
      "countryCode": "US"
    }
  ]
}

我可以按如下方式检索控制器中的数据:

@RequestMapping(value = "/stuffs", method = RequestMethod.POST)
public String invoices(@RequestBody Map<String, List <Stuff>> stuffs) {

    return "Hooray";
}

我真正想做的只是将一个列表传入控制器;即:

@RequestMapping(value = "/stuffs", method = RequestMethod.POST)
public String invoices(@RequestBody List <Stuff> stuffs) {

    return "I'm sad that this won't work.";
}

但是,杰克逊不喜欢这样。我得到的错误如下:

无法读取 JSON 文档:无法反序列化 java.util.ArrayList out of START_OBJECT token\n at [Source: java.io.PushbackInputStream@2a30a2f4;行:1,列:1];嵌套的 例外是 com.fasterxml.jackson.databind.JsonMappingException: Can 不在 START_OBJECT 中反序列化 java.util.ArrayList 的实例 令牌\n 在 [来源:java.io.PushbackInputStream@2a30a2f4;线:1, 列:1]

我无法发送以下内容(因为它不是有效的 JSON):

    {
      [
        {
          "thingId": 1,
          "thingNumber": "abc",
          "countryCode": "ZA"
        },
        {
          "thingId": 2,
          "thingNumber": "xyz",
          "countryCode": "US"
        }
      ]
    }

我确信这很简单,但我无法从 StackOverflow 和 Google 搜索中提取答案。

任何帮助将不胜感激! :)

【问题讨论】:

    标签: java json spring spring-boot jackson


    【解决方案1】:

    请注意,如果您尝试获取没有 Java 类的 JSON 数组(在 OP 的问题中,该类是“Stuff”),您需要像这样设置 Spring Boot 控制器:

    @RequestMapping(value = "/stuffs", method = RequestMethod.POST)
    public String invoices(@RequestBody Map<String, Object> [] stuffs) {
    
        return "Hooray";
    }
    

    【讨论】:

      【解决方案2】:

      您只需要发送不带大括号的内容

         [
          {
            "thingId": 1,
            "thingNumber": "abc",
            "countryCode": "ZA"
          },
          {
            "thingId": 2,
            "thingNumber": "xyz",
            "countryCode": "US"
          }
        ]
      

      在你的控制器中,当你告诉 Jackson 它应该解析一个列表时,它应该是一个列表而不是一个包含列表的对象

      【讨论】:

      • 是的!一旦时间限制过去,我会选择这个作为接受的答案。你让我免于遭受巨大的挫折!
      猜你喜欢
      • 2017-02-09
      • 2015-07-30
      • 2020-09-27
      • 1970-01-01
      • 2016-06-27
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      • 2020-06-25
      相关资源
      最近更新 更多