Gson deserialization for Realm list of primitives

别说谁变了你拦得住时间么 提交于 2019-12-22 06:49:05

问题


I am using realm with gson. I have a modal which has a list of int type field. Realm does not support currently list of primitives. To solve this there is a solution. I created my RealmInt class.

import io.realm.RealmObject;

public class RealmInt extends RealmObject {
    private int val;

    public int getVal() {
        return val;
    }

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

I have a big modal object something like that..

public class Product extends RealmObject {
    @PrimaryKey
    private int productID;
    private int priority;
    private boolean isFavourite;
    .....
    .....
    .....
    private RealmList<Document> documents;
    private RealmList<ProductInfoGroup> productInfoGroups;
    private RealmList<RealmInt> categories;

I must deserialize the json array below to Product modals.

[{
        "productID": 776,
        "categories": [
            35
        ],
        "name": "",
        "priority": 3,
        ......
        "status": 2,
        "documents": [
            {
                "documentID": 74,
                "productID": 776,
                "name": null,
                ....
                "isDefault": true
            }
        ],
        "productInfoGroups": [
            {
                "productInfoGroupID": 1575,
                "productID": 776,
                .....
                "productInfos": [
                    {
                        "productInfoID": 2707,
                        "productInfoGroupID": 1575,
                        "title": "",
                        ...
                    },
                    {
                        "productInfoID": 2708,
                        "productInfoGroupID": 1575,
                        ...
                    },
                    {
                        "productInfoID": 2709,
                        .....
                    }
                ]
            }
        ],
        "lastUpdateDate": 130644319676570000,
        "isActive": true
    },....]

There is a solution here but it is not for big objects. I need to change only categories array and other deserialization must be done by default gson deserialization.


回答1:


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.



来源:https://stackoverflow.com/questions/29493101/gson-deserialization-for-realm-list-of-primitives

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