How to serialize using gson with @SerializedName annotation?

35,909

Solution 1

The solution

String fqlQuery = "SELECT uid, name, pic_square FROM user WHERE uid IN "
            + "(SELECT uid2 FROM friend WHERE uid1 = me() )";
    Bundle params = new Bundle();
    params.putString("q", fqlQuery);
    Session session = Session.getActiveSession();
    Request request = new Request(session, "/fql", params, HttpMethod.GET,
            new Request.Callback() {
                public void onCompleted(Response response) {
                    Log.i(TAG, "Result: " + response.toString());

                    try {
                        final GsonBuilder builder = new GsonBuilder();
                        final Gson gson = builder.create();
                        **//here i get Data values** 
                        JSONObject data = response.getGraphObject()
                                .getInnerJSONObject();
                        FacebookResponses facebookResponses = gson
                                .fromJson(data.toString(),
                                        FacebookResponses.class);

                        Intent i = new Intent(getActivity()
                                .getApplicationContext(),
                                FacebookUsersImages.class);
                        i.putExtra("facebookResponses", facebookResponses);
                        startActivity(i);

                        // Log.i(TAG, "Result finale : " +
                        // facebookResponses.toString());
                    } catch (JsonSyntaxException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            });
    Request.executeBatchAsync(request);

FacebookResponses Class

public class FacebookResponses implements Serializable {

private static final long serialVersionUID = 1L;

@SerializedName("data")
public FacebookRisp[] data;

public FacebookRisp[] getData() {
    return data;
}

public void setData(FacebookRisp[] data) {
    this.data = data;
}

@Override
public String toString() {
    return "FacebookResponses [data=" + Arrays.toString(data) + "]";
}
}

FacebookRisp Class

public class FacebookRisp implements Serializable {

private static final long serialVersionUID = 1L;

@SerializedName("pic_square")
private String pic_square;

@SerializedName("pic")
private String pic;

@SerializedName("pic_big")
private String pic_big;

@SerializedName("pic_small")
private String pic_small;

@SerializedName("uid")
private String uid;

public String getPic() {
    return pic;
}

public void setPic(String pic) {
    this.pic = pic;
}

public String getPic_big() {
    return pic_big;
}

public void setPic_big(String pic_big) {
    this.pic_big = pic_big;
}

public String getPic_small() {
    return pic_small;
}

public void setPic_small(String pic_small) {
    this.pic_small = pic_small;
}

@SerializedName("name")
private String name;

public String getPic_square() {
    return pic_square;
}

public void setPic_square(String pic_square) {
    this.pic_square = pic_square;
}

public String getUid() {
    return uid;
}

public void setUid(String uid) {
    this.uid = uid;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

@Override
public String toString() {
    return "FacebookRisp [pic_square=" + pic_square + ", pic=" + pic + ", pic_big=" + pic_big + ", pic_small=" + pic_small + ", uid=" + uid
            + ", name=" + name + "]";
}
}

Solution 2

set basic class fields that match the json filed names, add annotation @serialaziedName("name_of_field") and gson should do the rest of the job after you registered the class

Share:
35,909
alfo888_ibg
Author by

alfo888_ibg

Updated on July 09, 2022

Comments

  • alfo888_ibg
    alfo888_ibg almost 2 years

    This is my first approach to serialization using Gson. I recive facebook response to my android application like this:

         Result: {
            Response:  responseCode: 200, 
            graphObject: GraphObject{graphObjectClass=GraphObject, 
            state={
               "data":[{"pic_square":"https:\/\/fbcdn-profile-a.akamaihd.net\/xxx.jpg",
               "uid":"1020272xxxx852765","name":"Mister X"}
            }, 
            error: null, isFromCache:false
          }]}
    

    I created new Class but i dont't know how to fill...

    import java.io.Serializable;
    import java.util.Arrays;
    import com.google.gson.annotations.SerializedName;
    public class FacebookResponse  implements Serializable{
    
    private static final long serialVersionUID = -104137709256566564L;
    
    @SerializedName("data")
    private FacebookResponse[] data;
    
    
    @Override
    public String toString() {
    return "FacebookResponse [data=" + Arrays.toString(data) + "]";
    }    
    

    }

    In my main fragment:

     Request request = new Request(session,
                    "/fql",                         
                    params,                         
                    HttpMethod.GET,                 
                    new Request.Callback(){         
                        public void onCompleted(Response response) {
                            Log.i(TAG, "Result: " + response.toString());
                            final GsonBuilder builder = new GsonBuilder();
                            final Gson gson = builder.create();
                            FacebookResponse facebookResponse= gson.fromJson(response.toString(),FacebookResponse.class);
                        } 
                }); 
                Request.executeBatchAsync(request);      
    

    Thanks a lot for your help

  • alfo888_ibg
    alfo888_ibg over 10 years
    can you help me to fill FacebookResponse class? i have some problem with a complex JSON....
  • Maciej Boguta
    Maciej Boguta over 10 years
    String pic_square, int uid, String name, add annotations with same names (although im pretty sure its not really needed if the fields names are same as in the json)
  • alfo888_ibg
    alfo888_ibg over 10 years
    I get this erros : com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 26
  • DiscDev
    DiscDev about 8 years
    Why are you using @SerializedName when you don't need to?
  • Tom
    Tom over 7 years
    @DiscDev Specifying a serialised name is best practice; it decouples your field names from your network model. Consider a dev coming along and wondering why pic_big isn't using camelcase. He refactors it in an IDE to picBig. Whoops, now it's null all the time. It's not going to be immediately obvious as to why this is the case much of the time.
  • DiscDev
    DiscDev over 7 years
    @Tom that's a good point. It's too bad devs don't follow proper variable naming conventions/best practices. I could totally see myself causing the bug you reference. If I came across code with member variables named like this (in Java) I'd refactor it immediately. Thanks for that!