1

I am trying to parse and insert JSON response using Realm Database in Android. Below is the exception that I am ending up with:

io.realm.exceptions.RealmException: Could not create JSON array from string
at io.realm.Realm.createOrUpdateAllFromJson(Realm.java:396)
at mobile.login.LoginFragment$1.onResponse(LoginFragment.java:218)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:133)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)                                                                                atjava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)

JSON that I am trying to parse:

{
  "count": 1,
  "statuses": [
    {
      "id": 0,
      "name": "Visible",
      "count": 0,
      "sort_order": 0
    },
    {
      "id": "1",
      "name": "Invisible",
      "count": 0,
      "sort_order": "1"
    }]
}

Count.java Pojo

public class Count extends RealmObject{

    @PrimaryKey
    private int count;

    private RealmList<Statuses> statuses;

    public int getCount() {
        return count;
    }
    public void setCount(int count) {
        this.count = count;
    }
    public RealmList<Statuses> getStatuses() {
        return statuses;
    }
    public void setStatuses(RealmList<Statuses> statuses) {
        this.statuses = statuses;
    }
}

Statuses.java Pojo

public class Statuses extends RealmObject{
    @PrimaryKey
    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("count")
    @Expose
    private Integer count;
    @SerializedName("sort_order")
    @Expose
    private String sortOrder;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getCount() {
        return count;
    }
    public void setCount(Integer count) {
        this.count = count;
    }
    public String getSortOrder() {
        return sortOrder;
    }
    public void setSortOrder(String sortOrder) {
        this.sortOrder = sortOrder;
    }
}

This is how I try to parse and store the JSON :

Realm realm = Realm.getInstance(getContext());
realm.beginTransaction();
realm.createOrUpdateAllFromJson(Order.class, **"JSON STRING HERE"**);
realm.commitTransaction();

If someone could help me resolve this than thats really awesome. Thanks in advance!

Ilya Tretyakov
  • 6,848
  • 3
  • 28
  • 45
Haresh Chaudhary
  • 4,390
  • 1
  • 34
  • 57
  • I think there is something wrong with Your json. Have a look: http://stackoverflow.com/questions/29064868/how-i-can-use-realm-to-parse-a-large-json-and-storing-data and: https://github.com/realm/realm-java/issues/968 – Opiatefuchs Feb 10 '16 at 07:57

1 Answers1

3

Method createOrUpdateAllFromJson() expects that your root object in json is Array.

Your code works correctly for this json:

[{
  "count": 1,
  "statuses": [
    {
      "id": 0,
      "name": "Visible",
      "count": 0,
      "sort_order": 0
    },
    {
      "id": "1",
      "name": "Invisible",
      "count": 0,
      "sort_order": "1"
    }]
}]

Use createOrUpdateObjectFromJson() for adding only one object (thanks to @EpicPandaForce).


Here is the source code of createOrUpdateAllFromJson method

/**
 * Tries to update a list of existing objects identified by their primary key with new JSON data. If an existing
 * object could not be found in the Realm, a new object will be created. This must happen within a transaction.
 *
 * @param clazz type of {@link io.realm.RealmObject} to create or update. It must have a primary key defined.
 * @param json string with an array of JSON objects.
 * @throws java.lang.IllegalArgumentException if trying to update a class without a
 * {@link io.realm.annotations.PrimaryKey}.
 * @throws RealmException if unable to create a JSON array from the json string.
 * @see #createAllFromJson(Class, String)
 */
public <E extends RealmObject> void createOrUpdateAllFromJson(Class<E> clazz, String json) {
    if (clazz == null || json == null || json.length() == 0) {
        return;
    }
    checkHasPrimaryKey(clazz);

    JSONArray arr;
    try {
        arr = new JSONArray(json);
    } catch (JSONException e) {
        throw new RealmException("Could not create JSON array from string", e);
    }

    createOrUpdateAllFromJson(clazz, arr);
}
Ilya Tretyakov
  • 6,848
  • 3
  • 28
  • 45
  • 2
    Which also means he should try `createOrUpdateFromJson()` which doesn't expect an array but a single object. – EpicPandaForce Feb 10 '16 at 09:00
  • @llya Tretyakov : What would you recommend me as a solution as my server's response is something I can't change. – Haresh Chaudhary Feb 10 '16 at 17:11
  • 1
    @HareshChaudhary look at this method `createOrUpdateObjectFromJson()`. It can be used for adding one object (not an array) – Ilya Tretyakov Feb 10 '16 at 17:13
  • @llya : Should I convert the returned string having JSON array into JSON object and then re-convert that JSON object to string manually before I pass the details ? – Haresh Chaudhary Feb 10 '16 at 17:13
  • Thanks a lot @IIya for the idea, I had to add manually those both brackets in order to resolve this and yes, you were correct with your answer! – Haresh Chaudhary Feb 10 '16 at 23:18
  • @AndroidGeek can u pls help me jhttp://jsoneditoronline.org/?id=cc5a403d1bbd933c250069a9221fcc02 – Erum Aug 04 '17 at 05:31
  • @IlyaTretyakov pls check this http://jsoneditoronline.org/?id=cc5a403d1bbd933c250069a9221fcc02 how to solve – Erum Aug 04 '17 at 05:31