如何将以Json字符串表示的对象存储到Couchbase Lite中? [英] How to store object represented as Json string into Couchbase Lite?

查看:128
本文介绍了如何将以Json字符串表示的对象存储到Couchbase Lite中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

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

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

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
}

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

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.

感谢任何提示!

推荐答案

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

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

您提到,如果您使用的是RetroFit之类的内容,则是从服务器获取JSON: https://github.com/square/retrofit ,您将不必直接处理JSON.您仍然必须编写映射逻辑,但是您只需要将Web服务响应对象直接输入到bedfabase中即可.

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.

这篇关于如何将以Json字符串表示的对象存储到Couchbase Lite中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆