How to store object represented as Json string into Couchbase Lite?

血红的双手。 提交于 2020-01-24 17:53:27

问题


I use Couchbase Lite in my Android app. In the app, I retrieve a bunch of Json objects from a server which I want to store locally. But I can't seem to find a way to do that without prior having to serialize them into HashMap. Since the data is stored as Json anyway, that infers unnecessary overhead and results in a lot of boilerplate code.

If I should be more specific, this is a kind of Json I fetch:

    "events":[
        {
        "title":"event1",
        "venue":{
            "name":"venue1"
        }
    ]

I use Gson to convert what goes in the array to POJOs:

public final class Event {
    @SerializedName("title") private String title;
    @SerializedName("venue") private Venue venue;

    public static final class Venue {
        @SerializedName("name") private String name;

        public Map<String, Object> toMap() {
            Map<String, Object> docContent = new HashMap<String, Object>();
            docContent.put("name", name);
            return docContent;
        }
    }

    public Map<String, Object> toMap() {
        Map<String, Object> docContent = new HashMap<String, Object>();
        docContent.put("title", title);
        docContent.put("venue", venue.toMap());
        return docContent;
    }

    // getters left out
}

And then I use Java object to store it:

Document document = database.createDocument();
document.putProperties(event.toMap());

Embedding goes much deeper and there are much more fields. I feel there must be a way to make things easier.

Thanks for any hints!


回答1:


I haven't seen any way to directly store JSON in a couchbase document, but you may be able to simplify your POJOfication use some of the suggestions listed here: Convert Json to Map

You mentioned that you're getting your JSON from a server, if you used something like RetroFit: https://github.com/square/retrofit you wouldn't ever have to deal directly with JSON. You'd still have to write your mapping logic, but you'd be able to just feed the web service response objects right into couchbase.




回答2:


Here's an example of how to do this. If your JSON is in JSONString

ObjectMapper mapper = new ObjectMapper();  // Usually you only need one instance of this per app.
try {
    Map<String, Object> map = mapper.readValue(JSONString, Map.class);
    Document document = db.createDocument();
    document.putProperties(map);
} catch (IOException | CouchbaseLiteException ex) {
    ex.printStackTrace();
}


来源:https://stackoverflow.com/questions/29723692/how-to-store-object-represented-as-json-string-into-couchbase-lite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!