Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson deserialization for Realm list of primitives

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.

like image 211
kml_ckr Avatar asked Apr 07 '15 13:04

kml_ckr


1 Answers

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.

like image 166
Christian Melchior Avatar answered Sep 20 '22 18:09

Christian Melchior