Json to POJO mapping in Android

前端 未结 1 1939
你的背包
你的背包 2020-12-30 15:39

What are good practice for handling json over a Rest Framework in Android. For instance, if I get a certain json result as follow (or any other, I\'m just giving something m

相关标签:
1条回答
  • I like to create a response object per api endpoint where i map the response of the call.

    For the given example and using GSON, the response object would be something like the following

    public class Test
    {
        static String jsonString = 
        "{\"lifts\":" + 
        "   [{" +
        "      \"id\":26," +
        "      \"time\":\"2012-11-21T12:00:00Z\"," +
        "      \"capacity\":4," +
        "      \"price\":10," +
        "      \"from\": { " +
        "               \"description\":null," +
        "               \"city\": {" +
        "                         \"name\":\"Montreal\"" +
        "                       }" +
        "               }," +
        "        \"to\":{" +
        "               \"description\":\"24 rue de la ville\"," +
        "               \"city\":{" +
        "                       \"name\":\"Sherbrooke\"" +
        "                      }" +
        "              }," +
        "        \"driver\":{" +
        "                  \"first_name\": \"Benjamin\"," +  
        "                  \"image\":\"https://graph.facebook.com/693607843/picture?    type=large\"" +
        "                 }" +
        "        }" +
        "     ]}";
    
    
        public static void main( String[] args )
        {
            Gson gson = new Gson();
    
            Response response = gson.fromJson( jsonString, Response.class );
    
            System.out.println( gson.toJson( response ) );
        }
    
    
        public class Response
        {
            @SerializedName("lifts")
            List<Lift> lifts;
        }
    
        class Lift
        {
            @SerializedName("id")
            int id;
    
            @SerializedName("time")
            String time;
    
            @SerializedName("capacity")
            int capacity;
    
            @SerializedName("price")
            float price;
    
            @SerializedName("from")
            Address from;
    
            @SerializedName("to")
            Address to;
    
            @SerializedName("driver")
            Driver driver;
        }
    
        class Address
        {
            @SerializedName("description")
            String description;
    
            @SerializedName("city")
            City city;
        }
    
        class City
        {
            @SerializedName("name")
            String name;
        }
    
        class Driver
        {
            @SerializedName("first_name")
            String firstName;
    
            @SerializedName("image")
            String image;
        }
    }
    
    0 讨论(0)
提交回复
热议问题