【发布时间】:2019-08-05 01:33:23
【问题描述】:
我向外部 RESTful api 发出了一个 get 请求,并接收到一个具有此结构的 json 对象作为响应:
{
"data": {
"id": 1,
"name": "John Doe",
"email": "doe@john.com",
"urlPicture": "urlPicture.com/82819",
"address": {
"street": "My street",
"number": "29",
"city": "Nurnberg",
"country": "Germany"
}
}
}
我不需要此响应的所有内容,我只想将一些字段保存在数据库中。
我的 POJO 类类似于这个伪代码:
public class Data{
private User user;
// getters and setters
}
public class User{
private int id;
private String name;
private String urlPicture;
private String country;
// getters and setters
}
但是,当我尝试提取我想要的字段时,我在此字段中收到 null
public void testResponse(){
RestTemplate restTemplate = new RestTemplate();
Data data = new Data();
User user = new User();
Gson gson = new Gson();
String response = restTemplate.getForObject(
"https://apifrommyrequest.com/user/{id}",
String.class,
73442);
user = gson.fromJson(response, User.class);
System.out.println(user);
}
```
My output:
22:20:57.641 [main] DEBUG org.springframework.web.client.RestTemplate - HTTP GET https://apifrommyrequest.com/user/73442
22:20:57.672 [main] DEBUG org.springframework.web.client.RestTemplate - Accept=[text/plain, application/json, application/*+json, */*]
22:20:58.243 [main] DEBUG org.springframework.web.client.RestTemplate - Response 200 OK
22:20:58.247 [main] DEBUG org.springframework.web.client.RestTemplate - Reading to [java.lang.String] as "application/json;charset=UTF-8"
Data(id=0, name=null, urlPicture=null, country=null)
I really don't know how to do anymore.
【问题讨论】:
-
这不是有效的 JSON。用户中的
country不起作用,因为它是子对象的一部分。 -
那么,我需要为嵌套对象构造一个内部类,对吧?那么,为什么其他数据不起作用?
-
我不知道响应的真实情况如何,所以我无法判断。请修复您示例中的 JSON。
-
好的,我会尝试修复它,如果继续给出错误,我会编辑问题。谢谢
-
首先,打印您的
response。并且RestTemplate能够为您进行反序列化。
标签: java spring-boot gson resttemplate