【问题标题】:How to store object represented as Json string into Couchbase Lite?如何将表示为 Json 字符串的对象存储到 Couchbase Lite 中?
【发布时间】:2015-06-25 18:00:37
【问题描述】:

我在我的 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());

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

感谢任何提示!

【问题讨论】:

    标签: java android json serialization couchbase-lite


    【解决方案1】:

    以下是如何执行此操作的示例。如果您的 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();
    }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 到目前为止,我最终重新发明了轮子,并基于反射 API 编写了我自己的自定义 POJO-to-map (de)serializer,这在性能方面无疑是一个非常丑陋的解决方案。我想我会研究改造,这似乎是一种方法。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-04
      • 1970-01-01
      相关资源
      最近更新 更多