7

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 more complex):

{"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"
             }
    }
]}

1) Should I handle the result manually and get each value to populate my ui... (Not really)

2) Should I create a POJO for each object (to handle the mapping, with JSONObject). In my example, I will have to create a lift object that handle all the parameters and even create more POJO, to use for instance image and probably locations. (so basically, I constantly need to check my api rest framework to see how my object are done on server side, I'm duplicating my models from server to the android client).

3) Is there any framework to handle the mapping (serialize and deserialization).

I'm currently using option number 2, but was wondering if there was something better out there. It's working for me so far, for receiving and sending.

Robert Estivill
  • 12,369
  • 8
  • 43
  • 64
fneron
  • 1,057
  • 3
  • 15
  • 39

1 Answers1

10

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;
    }
}
Robert Estivill
  • 12,369
  • 8
  • 43
  • 64
  • Interesting. I'll have a look at GSON, I've heard about it but never really took the time to check it since it was working just fine with JSONObject. – fneron Nov 20 '12 at 04:13
  • Do you have a example project using it? – fneron Nov 20 '12 at 18:56
  • I don't have anything publicly available. But it's pretty easy to use. You basically do: Gson gson = new Gson(); Response r = gson.fromJson( jsonString, Response.class ); and you are done :) – Robert Estivill Nov 20 '12 at 18:58
  • I've edited the answer with a full Test class that contains a main method that parses the given string into a Response instance, and writes it back to json. – Robert Estivill Nov 20 '12 at 19:06
  • GSON would use reflection to populate the fields, so you should add the getters/setters for your own sanity ;) – Robert Estivill Nov 20 '12 at 20:23
  • What if Json format changes from the backend and app crashes ? how to handle this kind of situation? – Karan sharma Apr 03 '18 at 13:29
  • can anyone tell the shortcut keys to add postman response of api to model class in android – s.j Apr 25 '20 at 18:02