简体   繁体   English

SpringBoot使用Jackson来反序列化Java中的JSON数组

[英]SpringBoot deserialize a JSON array in Java using Jackson

I am currently writing a SpringBoot application that retrieves a JSON array from an external API. 我目前正在编写一个SpringBoot应用程序,该应用程序从外部API检索JSON数组。 The part of the JSON I need looks like: 我需要的JSON部分如下所示:

{
"users": [
    "id": 110,
    "name": "john"
  ]
}

In my Controller I am doing the following: 在我的控制器中,我正在执行以下操作:

 ResponseEntity<Users> response = restTemplate
    .exchange(url, headers, Users.class);

return response

I then have a Users class that looks like: 然后,我有一个Users类,看起来像:

@JsonProperty("id")
public String id;
@JsonProperty("name")
public string name;

How can I access the information inside the JSON array? 如何访问JSON数组中的信息?

Thanks in advance. 提前致谢。

The JSON you posted above is not correct. 您上面发布的JSON不正确。 It needs to be: 它必须是:

{
   "users": [
       {
          "id": 110,
          "name": "john"
       }
    ]
}

and whatever object is used needs a list of Users . 无论使用什么对象都需要一个Users列表。

The other thing is you restTemplate call is wrong, you are expecting the call to return ResponseEntity<Opportunities> class yet when in your restTemplate you are giving it the User class and that will return ResponseEntity<User> instead 另一件事是restTemplate调用是错误的,您期望该调用返回ResponseEntity<Opportunities>类,但是在restTemplate中给它提供User类时,它将返回ResponseEntity<User>

Instead of loading into a POJO based on your return type you need to accept list of Users. 无需根据您的返回类型加载到POJO中,您需要接受“用户”列表。

You cannot accept List of user class in ResponseEntity you need to first cast into object class. 您不能在需要首先转换为对象类的ResponseEntity中接受用户类的列表。

ResponseEntity<Object> response = restTemplate .exchange(url, headers, Object.class);

Then you need to convert it into list of users. 然后,您需要将其转换为用户列表。

List<Users> usersList = (List<Users>) response.getBody();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM