使用Spring RestTemplate将嵌套的JSON对象映射到Java类 [英] Map Nested JSON Objects to Java Classes with Spring RestTemplate

查看:1385
本文介绍了使用Spring RestTemplate将嵌套的JSON对象映射到Java类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这可能很简单。但是,我无法让它工作。

I know this may be simple. However, I just can't get it to work.

所以我试图使用Spring RestTemplate来映射我的JSON数据。我有一个来自休息电话的JSON响应。

So I am trying to use Spring RestTemplate to map my JSON data. I have following JSON response from a rest call.

{
  "message":"ok",
  "status":"ok",
  "data":[
      {"Name":"Yo",
       "Address":"100 Test Rd"},
      {...},
      {...}
   ]
}

这是我试图将它映射到的类。

And here is the class I am trying to map it to.

@JsonIgnoreProperties(ignoreUnknown = true)
public class Response implements Serializable {

  private String message;
  private String status;
  private List<Data> data;

  // I could also use a array instead
  // private Data[] data;
}

这是我的数据类:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Data implements Serializable {

  private String Name;
  private String Address;
}

以下是我用来调用RestTemplate的代码:

Here is the code I used to call RestTemplate:

public Reponse getResponse() {
    ResponseEntity<Reponse> responseEntity = restTemplate.getForEntity(Url, Reponse.class);

    return responseEntity.getBody();
}

现在出现了问题。我能够获得消息和状态,但是当我尝试记录/打印数据时,它显示为null。不完全确定这里发生了什么。我真的可以用一些帮助。谢谢。

Now here comes the problem. I was able to get "message" and "status", But when I try to log/print data, it shows null. Not exactly sure what's going on here. I really could use some help. Thanks.

推荐答案

我遇到类似的问题,RestTemplate也没有将嵌套的JSON对象映射到我的类模型,经过多次挫折我决定使用RestTemplate将我的JSON检索为String(而不是直接转换为我的目标对象),然后使用google Gson库将我的String转换为我的目标实体。

I was having a similar issue with RestTemplate not mapping nested JSON objects to my class model also, after much frustration I decided to retrieve my JSON as a String(instead of converting directly to my target object) using RestTemplate and then use the google Gson library to convert my String to my target entity.

pom.xml

<dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.2.4</version>
    </dependency>

调用RestTemplate的代码:

code to call RestTemplate:

 ResponseEntity<String> responseEntity = restTemplate.getForEntity(Url,String.class);
Gson gson = new GsonBuilder().create();
Response reponse = gson.fromJson(responseEntity , Response.class);

不幸的是我无法找到为什么我的嵌套对象没有使用RestTemplate首先映射但是我希望这个解决方法有所帮助!

Unfortunately I was unable to find out why my nested objects were not mapped using RestTemplate the first place but I hope this workaround helps!

这篇关于使用Spring RestTemplate将嵌套的JSON对象映射到Java类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆