领域createAllFromJson引发BEGIN_ARRAY但被BEGIN_OBJECT异常

时间:2018-06-30 08:34:50

标签: android json realm retrofit realm-migration

我正在开发一个android移动应用程序,并且能够使用改造功能下载json文件并将其保存在本地存储中(在下载文件夹下)。但是,当我使用createAllFromJson将json文件的内容插入到reaml数据库中时,它会引发异常:BEGIN_ARRAY但是BEGIN_OBJECT

我提到了this,但是没有运气。

这是代码段:

JSON:

{
    "id": "2.1",
    "description": "Initial release",
    "version_external_id": "",
    "released": false,
    "source": {
        "created_on": "2018-01-08T13:02:37.017",
        "name": "Classification",
    },
    "items": [
        {
            "type": "Item",
            "id": "1",
            "display_name": "TV",
            "descriptions": "Household item",
        },
        {
            "type": "Item",
            "id": "2",
            "display_name": "CD Player",
            "descriptions": "Household item",
        }
    ]
}

型号:

public class ItemList extends RealmObject {

    @SerializedName("items")
    private RealmList<Item> getItems;
}

public class Item extends RealmObject
{
    private String id;
    private String type;
    private String display_name;
    private String descriptions;
//getter and setters...
}

读取json并将数据插入领域数据库的方法

private void populateItemList() {
        Realm realm = Realm.getDefaultInstance();
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                File file = new File(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"items.json");
                try {
                    FileInputStream stream = new FileInputStream(file);
                realm.createAllFromJson(ItemList.class, stream);

                }catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    if(realm.isInTransaction())
                        realm.cancelTransaction();
                    e.printStackTrace();
                }
            }
        });
    }

1 个答案:

答案 0 :(得分:1)

我将createAllFromJson更改为createObjectFromJson,现在可以正常使用了。