Search code examples
androidjsongsonpojo

Gson fromJson to different Class


I am writing my first android app and have very limited experience in parsing Json data back into POJO's. I am using GSON, and its mathod fromJson(). It is working somewhat but not all the classes are getting made.

The class i am serializing is

public class User  extends Model
{
   public String id;
   public String name;
   public List<User> friends = new ArrayList<User>();
   public List<Match> matches = new ArrayList<Match>();
}

Is it possible to parse the User into a class called User. but the List of Users into another Class with a different name and with much less parameters


Solution

  • Create and register a type adapter for List. Creating it looks something like this:

    private final TypeAdapter<List<User>> listOfUsersTypeAdapter = new TypeAdapter<List<User>>() {
        @Override public void write(JsonWriter out, List<User> value) throws IOException {
            out.beginArray();
            for (User user : value) {
                out.value(user.id);
            }
            out.endArray();
        }
        @Override public List<User> read(JsonReader in) throws IOException {
            in.beginArray();
            List<User> result = new ArrayList<User>();
            while (in.hasNext()) {
                User user = new User();
                user.id = in.nextString();
            }
            in.endArray();
            return result;
        }
    }.nullSafe();
    

    And register it when you create your Gson object:

        Gson gson = new GsonBuilder()
            .registerTypeAdapter(new TypeToken<List<User>>() {}.getType(), listOfUsersTypeAdapter)
            .create();
    

    I haven't tested this but it should work. Note that when you deserialize your users won't have any of their friends or matches fields filled in. You can reconstruct that from the graph in a post-processing step. Or use GraphAdapterBuilder to do it automatically.