Best way to map json to Java object

I use restTemplate to do rquest for a servlet that returns a very simple representation of an object in json.

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

And I have a DTO with these two fields and the corresponding setters and getters. I would like to know how to create an object using this json response without having to “parse” the response.

+2
source share
3 answers

Personally, I would recommend Jackson. Its quite lightweight, very fast and requires a very small configuration. Here is an example of deserialization:

@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);
+6
source

Here is an example of using Google Gson .

public class MyObject {

  private String id;
  private String name;

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

And access it:

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

, , . , , .

+3
+2
source

Source: https://habr.com/ru/post/1667430/


All Articles