问题
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