Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

And I have a DTO with those 2 fields and the corresponding setters and getters. What I would like to know is how to create the object using that json response without having to "parse" the response.

like image 827
Quantum_Entanglement Avatar asked Jan 30 '12 18:01

Quantum_Entanglement


3 Answers

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);
like image 197
Perception Avatar answered Nov 11 '22 19:11

Perception


Here's an example using 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.

like image 26
Marvin Pinto Avatar answered Nov 11 '22 17:11

Marvin Pinto


http://code.google.com/p/json-simple/ is nice and lightweight for this

like image 39
Gus Avatar answered Nov 11 '22 18:11

Gus