Gson deserialization for Realm list of primitives

十年热恋 提交于 2019-12-05 09:17:28

You must specify a custom type adapter for each variable that differs from the JSON representation. All other objects are handled automatically. In your case it is only the categories variable as the rest of variables should map automatically.

JSON:

[
    { "name"  : "Foo",
      "ints" : [1, 2, 3]
    },
    { "name"  : "Bar",
      "ints" : []
    }
]  

Model classes:

public class RealmInt extends RealmObject {
    private int val;

    public RealmInt() {
    }

    public RealmInt(int val) {
        this.val = val;
    }

    public int getVal() {
        return val;
    }

    public void setVal(int val) {
        this.val = val;
    }
}

public class Product extends RealmObject {

    private String name;
    private RealmList<RealmInt> ints;

    // Getters and setters
}

GSON configuration:

Gson gson = new GsonBuilder()
        .setExclusionStrategies(new ExclusionStrategy() {
            @Override
            public boolean shouldSkipField(FieldAttributes f) {
                return f.getDeclaringClass().equals(RealmObject.class);
            }

            @Override
            public boolean shouldSkipClass(Class<?> clazz) {
                return false;
            }
        })
        .registerTypeAdapter(new TypeToken<RealmList<RealmInt>>() {}.getType(), new TypeAdapter<RealmList<RealmInt>>() {

            @Override
            public void write(JsonWriter out, RealmList<RealmInt> value) throws IOException {
                // Ignore
            }

            @Override
            public RealmList<RealmInt> read(JsonReader in) throws IOException {
                RealmList<RealmInt> list = new RealmList<RealmInt>();
                in.beginArray();
                while (in.hasNext()) {
                    list.add(new RealmInt(in.nextInt()));
                }
                in.endArray();
                return list;
            }
        })
        .create();

JsonElement json = new JsonParser().parse(new InputStreamReader(stream));
List<Product> cities = gson.fromJson(json, new TypeToken<List<Product>>(){}.getType());

If you have multiple wrapper variables like RealmInt you need to define a TypeAdapter for each. Also note that the TypeAdapter above expect to always encounter an array. if you JSON might send null instead of [] you will need additional checking for that in the TypeAdapter.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!