我正在开发一个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();
                }
            }
        });
    }

最佳答案

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

07-24 15:18