yahoo / squidb

SquiDB is a SQLite database library for Android and iOS
https://github.com/yahoo/squidb/wiki
Apache License 2.0
1.31k stars 132 forks source link

Serialize any object to JSON #189

Closed iambibhas closed 8 years ago

iambibhas commented 8 years ago

With version 3.0, Is there any easy way to serialize an object to JSON without changing their model spec? I don't want to define columns as JSONColumn. Just want to take an object of a model and serialize it to JSON.

sbosley commented 8 years ago

So in other words you'd like to flatten a SquiDB model object to a set of key-value pairs as JSON? This isn't a built-in function, but it should be very easy to implement yourself -- you can call getMergedValues() on any SquiDB model object to get a set of key-value pairs for the current state of that model. This will be represented as a ValuesStorage object, on which you can call valuesSet() to get a Set<Map.Entry<String, Object>>, and then write those key-value pairs to a JSON string using your favorite JSON library.

This also isn't restricted to 3.0 -- getMergedValues() exists in 2.0 as well, although it returns a ContentValues. The same idea would apply though. Hope that helps!

iambibhas commented 8 years ago

@sbosley Thanks! That worked!

public JSONObject modelObjectToJson(TableModel obj) {
    JSONObject jobj = new JSONObject();
    try {
        for (Map.Entry<String, Object> s : obj.getMergedValues().valueSet()) {
            jobj.put(s.getKey(), s.getValue() == null ? "" : s.getValue());
        }
    } catch (JSONException e) {
        Log.d(this.toString(), e.getMessage());
        e.printStackTrace();
    }
    return jobj;
}

I was thinking about the next step and taking a cursor and turn that into a JSONArray. But having trouble guessing the model type and iterating over the cursor.

sbosley commented 8 years ago

👍 glad that worked!

In terms of guessing the model type, I'd suggest passing around the model class that you passed to SquidDatabase.query() and using that. You can then get an instance using modelClass.newInstance() and use readPropertiesFromCursor() to populate it. The cursor iteration itself is just like iterating over a standard android cursor; all the same methods are available.