Best way to map json to a Java object

前端 未结 3 642
名媛妹妹
名媛妹妹 2021-01-13 12:49

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\":         


        
3条回答
  •  [愿得一人]
    2021-01-13 13:19

    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.

提交回复
热议问题