user2456977
user2456977

Reputation: 3964

Gson convert from JSON to Java object

(I am very new to Gson and Json so please forgive me if this is a silly question)

Here is the response from my POST request:

String getResponse = ({"user_id":"1","device_id":"0","user_name":"jdoe","first_name":"John","last_name":"Doe"});

After getting the response, I use the following method to put the JSON values into my Java object:

 FacebookUser facebookUser = new FacebookUser();

 JSONObject responseObject = new JSONObject(getResponse);

    Iterator<String> iter = responseObject.keys();
    while (iter.hasNext()) {
        String key = iter.next();

        switch (key) {

            case "user_id":
                try {
                    Object value = responseObject.get(key);
                    facebookUser.setUserId((String) value);
                } catch (JSONException e) {
                    Log.d("JsonException", "error" + e.toString());
                }
                break;

            case "device_id":
                try {
                    Object value = responseObject.get(key);
                    facebookUser.setDeviceId((String) value);
                } catch (JSONException e) {
                    Log.d("JsonException", "error" + e.toString());
                }
                break;

            case "user_name":
                try {
                    Object value = responseObject.get(key);
                    facebookUser.setUsername((String) value);
                } catch (JSONException e) {
                    Log.d("JsonException", "error" + e.toString());
                }
                break;

            case "first_name":
                try {
                    Object value = responseObject.get(key);
                    facebookUser.setFirstName((String) value);
                } catch (JSONException e) {
                    Log.d("JsonException", "error" + e.toString());
                }
                break;

            case "last_name":
                try {
                    Object value = responseObject.get(key);
                    facebookUser.setLastName((String) value);
                } catch (JSONException e) {
                    Log.d("JsonException", "error" + e.toString());
                }
                break;
        }
    }    

This works great and all the values are put in my FacebookUser object. But obviously this is very tedious work especially in a case where I would get a response with 100 key/value pairs.

So I tried using Gson to make this work all at once:

        String getResponse = ({"user_id":"1","device_id":"0","user_name":"jdoe","first_name":"John","last_name":"Doe"});

        FacebookUser facebookUser = new FacebookUser();

        Gson gson = new GsonBuilder()
                .disableHtmlEscaping()
                .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
                .setPrettyPrinting()
                .serializeNulls()
                .create();

        FacebookUser facebookUser = gson.fromJson(getResponse,
                        FacebookUser.class);

However, all the facebookUser fields are null...

Can someone please help?

Here is my FacebookUser class:

public class FacebookUser implements Serializable{

    String userId;
    String deviceId;
    String username;
    String firstName;
    String lastName;

    public FacebookUser() { //default ctor
    }

    ... a bunch of getters
    ... a bunch of setters
}

Upvotes: 0

Views: 369

Answers (2)

florent champigny
florent champigny

Reputation: 979

Gson don't know find property that matches json fields because of underscores, you have to explain how work with _

`

final GsonBuilder builder = new GsonBuilder();

builder.setDateFormat(DateFormat.LONG);
builder.setPrettyPrinting();
builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
final Gson gson = builder.create();

FacebookUser facebookUser = gson.fromJson(getResponse,FacebookUser.class);

`

With this gson this should works

Upvotes: 0

Nathua
Nathua

Reputation: 8826

You need to match exact names, you can use SerializedName annotation

@SerializedName("user_id") String userId;

Upvotes: 1

Related Questions