使用 Spring RestTemplate 将嵌套的 JSON 对象映射到 Java 类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28893713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:22:06  来源:igfitidea点击:

Map Nested JSON Objects to Java Classes with Spring RestTemplate

javajsonspringresttemplate

提问by Ren

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

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

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

所以我试图使用 Spring RestTemplate 来映射我的 JSON 数据。我有以下来自休息调用的 JSON 响应。

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

Here is my Data class:

这是我的数据类:

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

  private String Name;
  private String Address;
}

Here is the code I used to call RestTemplate:

这是我用来调用 RestTemplate 的代码:

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

    return responseEntity.getBody();
}

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.

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

回答by O. Coburn

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.

我也遇到了类似的问题,RestTemplate 没有将嵌套的 JSON 对象映射到我的类模型,在非常沮丧之后,我决定使用 RestTemplate 将我的 JSON 作为字符串检索(而不是直接转换为我的目标对象),然后使用谷歌 Gson 库将我的字符串转换为我的目标实体。

pom.xml

pom.xml

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

code to call RestTemplate:

调用 RestTemplate 的代码:

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

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!

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

回答by Abhishek

I had a similar issue when reading Json data from REST API using Rest Template. To resolve declare getters and setters for the List:

使用 Rest 模板从 REST API 读取 Json 数据时,我遇到了类似的问题。要解决 List 的声明 getter 和 setter:

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

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

 // getters and Setters for the list. 


}

The RestTemplate will internally map the values from the listarray to the corresponding array.

RestTemplate 将在内部将值从 listarray 映射到相应的数组。

回答by Isank

Annotate property "data" with @JsonUnwrapped as below

使用@JsonUnwrapped 注释属性“数据”如下

@JsonIgnoreProperties(ignoreUnknown = true)
public class Response implements Serializable {
    private String message;
    private String status;
    @JsonUnwrapped
    private List<Data> data;
}

回答by James

I ran into the same issue. Annotate with @JsonProperty:

我遇到了同样的问题。注释@JsonProperty

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

    @JsonProperty("Name")
    private String name;

    @JsonProperty("Address")
    private String address;

    // getters / setters for name and address

}

The fields of your Dataclass should now get populated, and you can name your fields independent of the JSON representation (e.g. nameinstead of Name).

你的Data类的字段现在应该被填充,你可以独立于 JSON 表示命名你的字段(例如,name而不是Name)。

回答by Tharindu Rathnayake

I know this is an old thread.

我知道这是一个旧线程。

But for anyone having the same problem, you can use MappingHymanson2HttpMessageConverterfor this purpose with Hymanson.

但是对于任何有同样问题的人,您可以将MappingHymanson2HttpMessageConverterHymanson 用于此目的。

Please refer the answer given in thisthread.

请参阅线程中给出的答案。

回答by sayan

Please use private List<Data> data = new AllarList<Data>( ); and please provide getters( ) and setters( ) methods in both the classes.

请使用private List<Data> data = new AllarList<Data>( ); 并且请在两个类中提供 getters() 和 setters() 方法。

Put @JsonInclude(Include.NON_EMPTY)above Data class

放在@JsonInclude(Include.NON_EMPTY)数据类之上

Please add below dependencies under section at your main POM.xml file and do maven compile. Then I guess your issue will get resolved.

请在您的主要 POM.xml 文件的部分下添加以下依赖项并进行 maven 编译。那么我想你的问题会得到解决。

        <dependency>
            <groupId>com.fasterxml.Hymanson.core</groupId>
            <artifactId>Hymanson-annotations</artifactId>
            <version>2.2.3</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.Hymanson.core</groupId>
            <artifactId>Hymanson-databind</artifactId>
            <version>2.2.3</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.Hymanson.datatype</groupId>
            <artifactId>Hymanson-datatype-joda</artifactId>
            <version>2.1.1</version>
        </dependency>

        <dependency>
            <groupId>org.codehaus.Hymanson</groupId>
            <artifactId>Hymanson-mapper-asl</artifactId>
            <version>1.8.8</version>
        </dependency>

回答by Andrey

If you need only print data, you can do this

如果你只需要打印数据,你可以这样做

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.getForEntity(
    "your url",
    String.class);

System.out.println(response);