用gson将JsonArray带到Realm

时间:2017-07-13 14:43:56

标签: java android json gson realm

我有一个问题是将jsonarray存储到领域 我得到了例外

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY

oncreat活动我这样做

Realm.init(getApplicationContext());
    RealmConfiguration realmConfiguration = new RealmConfiguration.Builder().build();

    Realm.setDefaultConfiguration(realmConfiguration); // Make this Realm the default;
    realm.getInstance(realmConfiguration);

但是realm变量为null

我的保存代码是

adressModelListrealm = gson.fromJson(parentArray, AdressModelRealm.class);

当我尝试使用新代码存储时

List<AdressModelRealm> woList = gson.fromJson(parentArray, new TypeToken<List<AdressModelRealm>>() {
                    }.getType());
                    realm.beginTransaction();
                    realm.copyToRealm(woList);
                    realm.commitTransaction();

我得到一个nullPointexecption

我的模特:

public class AdressModelRealm extends RealmObject {




private String SNR;
private String ADR_2_8;     // Adressnummer
private String ADR_20_30;   // Adressname

......还有更多有吸气剂的人;

和我的json数组:

 [{
    "SNR": "6",
    "ADR_2_8": "10000",
    "ADR_20_30": "Kunde Inland",
    "ADR_2332_20": "+49 (1234) 56789-00",
    "ADR_242_20": "+49 (1234) 56789-99",
    "ADR_2187_46": "Inlandstraße",
    "ADR_2170_11": "1",
    "ADR_110_10": "12345",
    "ADR_2233_40": "Inlandsort",
    "ADR_1330_60": "inlandzk@meine-firma-homepage.de"
 }]

我可以帮助任何人吗?

1 个答案:

答案 0 :(得分:0)

您将要使用JSON Schema to POJO,以便将对象从JSON转换为Java对象。然后你想要拥有AddressModel extend RealmObject,这样你就可以把Java对象放到这样的领域了

Realm.init();
Realm realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                       realm.copyToRealmOrUpdate(new AddressModel(//constructor);
                    }
                });

Here是关于JSONSchemaToPOJO如何运作的好教程。