2017-05-16 37 views
0

我张贴这样的事:邮政JSON数组到Spring引导RestController

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

我很想do只是将一个List of Stuff传入控制器;即:

@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中的实例进行START_OBJECT令牌的\ n: [email protected];行:1,列:1];嵌套0​​异常是com.fasterxml.jackson.databind.JsonMappingException:可以 不反序列化java.util.ArrayList的实例超出START_OBJECT token [n] [Source:[email protected];行:1, 列:1]

我不能在以下发送(因为它不是有效的JSON):

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

我敢肯定,这是简单的东西,但我不能蒸馏的从我的StackOverflow和谷歌搜索答案。

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

回答

1

你只需要发送这个没有大括号

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

在你的控制器当你告诉杰克逊,它应该被解析列表它应该是一个列表不包含列表

对象
+0

是的!一旦时间限制通过,我会选择这个作为接受的答案。你从一些巨大的挫折中拯救了我! – orrymr

+1

很高兴我能帮上忙 –

0

需要注意的是,如果你想(在OP的问题类别是“东西”),以获得JSON数组没有一个Java类,您将需要设置的弹簧引导控制器是这样的:

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

    return "Hooray"; 
}