1

I'm developing an android mobile app and I was able to use retrofit to download a json file and kept it in the local storage (under download folder). However, when I use createAllFromJson to insert the contents of the json file into the reaml database, it throws the exception: BEGIN_ARRAY but was BEGIN_OBJECT

I referred to this but with no luck.

Here is the code snippet:

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",
        }
    ]
}

Models:

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

Method to read json and insert data into realm database

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();
                }
            }
        });
    }
Dee_wab
  • 1,171
  • 1
  • 10
  • 23
aby
  • 810
  • 6
  • 21
  • 36
  • Your JSON seems to be wrong. Can you try this once? { "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" } ] } – Sanchita Santra Jun 30 '18 at 10:14

1 Answers1

1

I changed the createAllFromJson to createObjectFromJson and it is working now.

aby
  • 810
  • 6
  • 21
  • 36