2

我在我的 Android 应用程序中使用 Couchbase Lite。在应用程序中,我从要在本地存储的服务器检索一堆 Json 对象。但我似乎无法找到一种方法来做到这一点,而无需事先将它们序列化为 HashMap。由于数据无论如何都存储为 Json,这会导致不必要的开销并导致大量样板代码。

如果我应该更具体一点,这是我获取的一种 Json:

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

我使用 Gson 将数组中的内容转换为 POJO:

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
}

然后我使用 Java 对象来存储它:

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

嵌入更深,领域也更多。我觉得一定有办法让事情变得更容易。

感谢您的任何提示!

4

2 回答 2

1

我还没有看到任何将 JSON 直接存储在 couchbase 文档中的方法,但是您可以使用此处列出的一些建议来简化您的 POJOfication:将 Json 转换为 Map

您提到您从服务器获取 JSON,如果您使用 RetroFit 之类的东西:https ://github.com/square/retrofit ,您将不必直接处理 JSON。您仍然需要编写映射逻辑,但您可以直接将 Web 服务响应对象提供给 couchbase。

于 2015-05-11T20:08:44.363 回答
0

这是如何执行此操作的示例。如果您的 JSON 在 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();
}
于 2016-09-14T16:21:44.847 回答