简体   繁体   English

将json映射到Java对象的最佳方法

[英]Best way to map json to a Java object

I'm using restTemplate to make a rquest to a servlet that returns a very simple representation of an object in json. 我正在使用restTemplate对servlet进行rquest,该servlet返回json中对象的非常简单的表示。

{
     "id":"SomeID"
     "name":"SomeName"
}

And I have a DTO with those 2 fields and the corresponding setters and getters. 我有一个带有这两个字段的DTO以及相应的setter和getter。 What I would like to know is how to create the object using that json response without having to "parse" the response. 我想知道的是如何使用该json响应创建对象而无需“解析”响应。

Personally I would recommend Jackson. 我个人会推荐杰克逊。 Its fairly lightweight, very fast and requires very little configuration. 它相当轻巧,速度非常快,只需要很少的配置。 Here's an example of deserializing: 以下是反序列化的示例:

@XmlRootElement
public class MyBean {
    private String id;
    private String name;

    public MyBean() {
        super();
    }

    // Getters/Setters
}


String json = "...";
MyBean bean = new ObjectMapper().readValue(json, MyBean.class);

Here's an example using Google Gson . 以下是使用Google Gson的示例。

public class MyObject {

  private String id;
  private String name;

  // Getters
  public String getId() { return id; }
  public String getName() { return name; }
}

And to access it: 并访问它:

MyObject obj = new Gson().fromJson(jsonString, MyObject.class);
System.out.println("ID: " +obj.getId());
System.out.println("Name: " +obj.getName());

As far as the best way, well that's subjective. 至于最好的方式,这是主观的。 This is one way you can accomplish what you need. 这是您可以实现所需目标的一种方式。

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

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