【问题标题】:Deserialize json array where attribute value is array java反序列化属性值为数组java的json数组
【发布时间】:2019-08-27 20:30:30
【问题描述】:

我知道这是非常基本的,但是当格式如下时,我在使用 jackson 反序列化 json 时遇到问题:

我创建了一个带有 id、name 和 place 的类 Person 并尝试使用 jackson 读取 API 调用的结果(使用 @JsonProperty 注释),但是当我调试 person 变量时为 null:

 json body:
  { people:[  
   {  
    "id":"0",
    "name":"Bob",
    "place":"Colorado",
   },
   {  
    "id":"1",
    "name":"John",
    "place":"Chicago",
   },
   {  
    "id":"2",
    "name":"Marry",
    "place":"Miami",
   }
 ]}


 RequestEntity<Void> reqEntity = RequestEntity.get(new URI(url))
                .accept(MediaType.APPLICATION_JSON)
                .build();

 ResponseEntity<List<Person>> persons = template.exchange(reqEntity, new ParameterizedTypeReference<List<Person>>() {});

【问题讨论】:

    标签: java arrays json jackson deserialization


    【解决方案1】:

    您应该将您的 List&lt;Person&gt; 包装在另一个 Response 对象中,该对象有一个 people 字段,包含您的列表:

    public class PeopleResponse {
        private List<Person> people;
    
        // getter and setter
    }
    

    然后你可以根据那个改变你的ResponseEntity

    ResponseEntity<PeopleResponse> response = template.exchange(reqEntity, new ParameterizedTypeReference<PeopleResponse>() {});
    List<Person> people = response.getBody().getPeople();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-08
      • 1970-01-01
      • 1970-01-01
      • 2014-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      相关资源
      最近更新 更多