Gson反序列化为Realm原语列表 [英] Gson deserialization for Realm list of primitives

查看:158
本文介绍了Gson反序列化为Realm原语列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用gson使用realm。我有一个模式,它有一个int类型字段的列表。领域不支持当前的基元列表。要解决这个问题,有一个解决方案。我创建了RealmInt类。

  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;
}
}

我有一个很大的模态对象。

  public class Product extends RealmObject {
@PrimaryKey
private int productID;
private int priority;
private boolean isFavourite;
.....
.....
.....
private RealmList< Document>文件;
private RealmList< ProductInfoGroup> productInfoGroups;
private RealmList< RealmInt>类别;

我必须将下面的json数组反序列化为Product modals。

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

此处,但它不适用于大对象。我只需要更改类别数组,其他反序列化必须通过默认的gson反序列化完成。

解决方案

您必须指定自定义类型适配器对于每个与JSON表示不同的变量。所有其他对象都会自动处理。在你的情况下,它只是类别变量,因为剩下的变量应该自动映射。



JSON:

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

模型类:

  public class RealmInt extends RealmObject {
private int val;
$ b $ 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>整数;

// Getters and setters
}

GSON配置:

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

@覆盖
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 {
//忽略
}

@覆盖
public Re almList< RealmInt> read(JsonReader in)抛出IOException {
RealmList< RealmInt> list = new RealmList< RealmInt>();
in.beginArray(); (in.hasNext()){
list.add(new RealmInt(in.nextInt()));
}
in.endArray();
返回列表;
}
})
.create();

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

如果您有像RealmInt这样的多个包装变量,您需要为每个变量定义一个TypeAdapter。另外请注意,上面的TypeAdapter期望总是遇到一个数组。如果您的JSON可能会发送 null 而不是 [] ,那么您需要在TypeAdapter中进行额外的检查。


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.

解决方案

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.

这篇关于Gson反序列化为Realm原语列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆