Joe Ginley
Joe Ginley

Reputation: 341

Json string to realm objects, fastest way

I have the following code that I am running in an AsyncTask. It works well but the following lines seem to make it 3-5 seconds slower when used. Is there a faster way to convert my json string into realm?

    //Load the local model data. params[0].toString() is a json string loaded from SharedPreferences.
    JsonParser jsonParser = new JsonParser();
    JsonObject o = (JsonObject)jsonParser.parse(params[0].toString());

    Realm realmThread = Realm.getInstance(visnetawrap.appModel);

    //work orders, total entries of 4000.
    JsonArray openWorkOrders = o.getAsJsonArray("work_orders");

    //Convert the lists so they can be used with realm.
    List<OpenOrderObject> woList = visnetawrap.gsonClient.fromJson(openWorkOrders.toString(), new TypeToken<List<OpenOrderObject>>() {
    }.getType());
    realmThread.beginTransaction();
    realmThread.copyToRealm(woList);
    realmThread.commitTransaction();

Upvotes: 4

Views: 4700

Answers (1)

Christian Melchior
Christian Melchior

Reputation: 20126

It depends on how well your JSON match your model classes. In the above code, you seems to do a lot of extra work converting between a string representation and a object model 2 times.

If you model matches your JSON 1:1 you can just use realm.createAllFromJson(OpenOrderObject.class, openWorkOrders). You don't have to convert it first using GSON unless GSON manipulates the input somehow. You can see more here: https://realm.io/docs/java/latest/api/io/realm/Realm.html#createAllFromJson-java.lang.Class-org.json.JSONArray-.

Also, it shouldn't really take seconds to parse this if your input is fairly small (which I guess it is since you are saving it in SharedPreferences), but note that Realm transactions are blocking, so if you have multiple background threads doing transactions they will block each other.

Upvotes: 4

Related Questions