gpt4 book ai didi

java - 将 JSON 数组发布到 Spring Boot RestController 中

转载 作者:行者123 更新时间:2023-12-02 16:16:11 24 4
gpt4 key购买 nike

我正在发布这样的内容:

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

我可以按如下方式检索 Controller 中的数据:

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

return "Hooray";
}

我真正想做的只是将一个东西列表传递到 Controller 中;即:

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

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

然而, jackson 不喜欢这样。我得到的错误如下:

Could not read JSON document: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token\n at [Source: java.io.PushbackInputStream@2a30a2f4; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token\n at [Source: java.io.PushbackInputStream@2a30a2f4; line: 1, column: 1]

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

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

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

如有任何帮助,我们将不胜感激! :)

最佳答案

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

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

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

关于java - 将 JSON 数组发布到 Spring Boot RestController 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43997857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com