Java 如何以JSON格式在couchbase lite android中插入数据

Java 如何以JSON格式在couchbase lite android中插入数据,java,android,json,couchbase,couchbase-lite,Java,Android,Json,Couchbase,Couchbase Lite,我是NoSQL数据库的新手。我想将以下JSON数据保存到CouchBase Lite中。有人能告诉我最好的方法吗 {"widget": { "window": { "title": "Sample Konfabulator Widget", "name": "main_window", "width": 500, "height": 500 }, "image": { "src": "Im

我是NoSQL数据库的新手。我想将以下JSON数据保存到CouchBase Lite中。有人能告诉我最好的方法吗

{"widget": {

    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "width": 500,
        "height": 500
    },
    "image": { 
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "alignment": "center"
    },
    "text": {
        "data": "Click Here",
        "size": 36,
        "style": "bold",
        "name": "text1",
        "hOffset": 250,
        "vOffset": 100,
        "alignment": "center",
        "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
}}    
我尝试使用下面的代码来实现这一点

public void insertSample(String widget,String control,ArrayList<eModel> details){

    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("control", control);
    properties.put("details", details);
    Document document = database.getDocument(widget);
    try {
        document.putProperties(properties);
    } catch (CouchbaseLiteException e) {
        Log.e("", "Cannot save document", e);
    }
}
然后我想在“窗口”字段下追加以下字段:


您需要像这样构造映射,以便像上面的json格式那样保存

 Map<String, Object> windowMap = new HashMap<String, Object>();
    windowMap.put("title","Sample Konfabulator Widget");
    windowMap.put("name","main_window");
    windowMap.put("width",500);
    windowMap.put("height",500);

    Map<String, Object> imageMap = new HashMap<String, Object>();
    imageMap.put("src","Images/Sun.png");
    imageMap.put("name","sun1");
    imageMap.put("hOffset",250);
    imageMap.put("vOffset",250);

    Map<String, Object> textMap = new HashMap<String, Object>();
    textMap.put("data","Click Here");
    textMap.put("size",36);


    Map<String, Object> memberMap = new HashMap<String, Object>();
    memberMap.put("window",windowMap);
    memberMap.put("image",imageMap);
    memberMap.put("text",textMap);

    Map<String, Object> widgetMap = new HashMap<String, Object>();
    widgetMap.put("widget",memberMap);

    try {
        document.putProperties(widgetMap);
    } catch (CouchbaseLiteException e) {
        Log.e("", "Cannot save document", e);
    }
Map windowMap=newhashmap();
put(“标题”,“示例Konfabulator小部件”);
windowMap.put(“名称”、“主窗口”);
窗口映射。放置(“宽度”,500);
窗口地图。放置(“高度”,500);
Map imageMap=newhashmap();
imageMap.put(“src”、“Images/Sun.png”);
imageMap.put(“名称”、“sun1”);
imageMap.put(“hOffset”,250);
imageMap.put(“vOffset”,250);
Map textMap=newhashmap();
textMap.put(“数据”,“单击此处”);
textMap.put(“大小”,36);
Map memberMap=newhashmap();
memberMap.put(“窗口”,windowMap);
memberMap.put(“图像”,imageMap);
memberMap.put(“text”,textMap);
Map widgetMap=newhashmap();
widgetMap.put(“小部件”,memberMap);
试一试{
文件属性(widgetMap);
}捕获(CouchBaselite异常){
Log.e(“,”无法保存文档“,e);
}

Couchbase Lite中文档的约束是
\u id
属性应该是唯一的。随着文档的更新,它会创建新的修订

更新文档有两种可能的方法:

  • putProperties
    :给定一个新的JSON对象,它将用该对象替换文档的正文
  • 更新
    :接受回调函数或块。它加载当前版本的属性,然后调用此函数,向其传递一个
    UnsavedRevision
    对象,该对象的属性是当前版本的可变副本。您的回调代码可以根据需要修改此对象的属性;返回后,将保存修改后的修订并成为当前修订
因此,要使用
图像
字典更新小部件文档,应使用更新方法:

final Map<String, Object> imageProperties = new HashMap<String, Object>();
imageProperties.put("src", "Images/Sun.png");
imageProperties.put("name", "sun1");
// ...

Document document = database.getDocument(widgetId);
document.update(new Document.DocumentUpdater() {
    @Override
    public boolean update(UnsavedRevision newRevision) {
        Map<String, Object> properties = newRevision.getUserProperties();
        properties.put("image", imageProperties);
        newRevision.setUserProperties(properties);
        return true;
    }
});
final Map imageProperties=new HashMap();
imageProperties.put(“src”、“Images/Sun.png”);
imageProperties.put(“名称”、“sun1”);
// ...
Document Document=database.getDocument(widgetId);
document.update(新的document.DocumentUpdater(){
@凌驾
公共布尔更新(未保存的修订版newRevision){
Map properties=newRevision.getUserProperties();
属性。放置(“图像”,imageProperties);
setUserProperties(属性);
返回true;
}
});

注意:建议使用类似Jackson的库来序列化/反序列化Java应用程序中的JSON和POJO模型(您可以阅读本文以查找更多信息)。

我也遇到了同样的问题。您需要遍历json的键,并使用putproperties添加每个对象。但是,对于JSONArray,需要使用ArrayList。我使用Jackson库遍历密钥(couchbase内部也使用该库)

试试看{
映射属性=新的HashMap();
JsonFactory工厂=新的JsonFactory();
ObjectMapper mapper=新的ObjectMapper(工厂);
//将json字符串转换为Jackson JsonNode
JsonNode rootNode=mapper.readTree(doc.toString());
迭代器it=rootNode.getFields();
while(it.hasNext()){
Map.Entry pair=it.next();
String key=pair.getKey().toString();
字符串值=pair.getValue().toString();
if(JSONDiffUtil.isJSONArray(值)){
logInfo(“它是一个json数组:”+键,模块);
ArrayNode arrNode=(ArrayNode)pair.getValue();
properties.put(键、节点);
} 
else if(key.startsWith(“”)){
Debug.logInfo(“跳过_rev”+键,模块);
} 
否则{
logInfo(“它是一个json对象:”+键,模块);
properties.put(key,pair.getValue());
}
}
文件、财产(财产);
}
捕获(CouchBaselite异常){
Debug.logInfo(“错误”,模块);
logInfo(例如getMessage(),模块);
}捕获(JsonProcessingException e){
logInfo(例如getMessage(),模块);
}捕获(IOE异常){
logInfo(例如getMessage(),模块);
}

有一个非常有用的链接,您可以在其中找到好的信息

如果要多次使用同一小部件值,可以更新it@pushpendrachauhan如果我更新旧数据呢?谢谢你的回答。我在运行时也在做同样的事情。我怎样才能找回这个。请在答案中添加该代码。您需要使用查看或所有文档查询来检索该代码,顺便说一句,请将其标记为answermate,实际上您是静态完成的,我需要动态追加。请更新答案。
 Map<String, Object> windowMap = new HashMap<String, Object>();
    windowMap.put("title","Sample Konfabulator Widget");
    windowMap.put("name","main_window");
    windowMap.put("width",500);
    windowMap.put("height",500);

    Map<String, Object> imageMap = new HashMap<String, Object>();
    imageMap.put("src","Images/Sun.png");
    imageMap.put("name","sun1");
    imageMap.put("hOffset",250);
    imageMap.put("vOffset",250);

    Map<String, Object> textMap = new HashMap<String, Object>();
    textMap.put("data","Click Here");
    textMap.put("size",36);


    Map<String, Object> memberMap = new HashMap<String, Object>();
    memberMap.put("window",windowMap);
    memberMap.put("image",imageMap);
    memberMap.put("text",textMap);

    Map<String, Object> widgetMap = new HashMap<String, Object>();
    widgetMap.put("widget",memberMap);

    try {
        document.putProperties(widgetMap);
    } catch (CouchbaseLiteException e) {
        Log.e("", "Cannot save document", e);
    }
final Map<String, Object> imageProperties = new HashMap<String, Object>();
imageProperties.put("src", "Images/Sun.png");
imageProperties.put("name", "sun1");
// ...

Document document = database.getDocument(widgetId);
document.update(new Document.DocumentUpdater() {
    @Override
    public boolean update(UnsavedRevision newRevision) {
        Map<String, Object> properties = newRevision.getUserProperties();
        properties.put("image", imageProperties);
        newRevision.setUserProperties(properties);
        return true;
    }
});
        try {
            Map<String, Object> properties = new HashMap<String, Object>();
            JsonFactory factory = new JsonFactory();
            ObjectMapper mapper = new ObjectMapper(factory);

            // convert you json string to Jackson JsonNode
            JsonNode rootNode = mapper.readTree(doc.toString());  

            Iterator<Map.Entry<String, JsonNode>> it = rootNode.getFields();
            while (it.hasNext()) {
                Map.Entry<String, JsonNode> pair = it.next();
                String key = pair.getKey().toString();
                String value = pair.getValue().toString();
                if (JSONDiffUtil.isJSONArray(value)) {
                    Debug.logInfo("its a json array: " + key, MODULE);
                    ArrayNode arrNode = (ArrayNode) pair.getValue();
                    properties.put(key, arrNode);
                } 
                else if (key.startsWith("_")) {
                    Debug.logInfo("skipping _rev" + key, MODULE);
                } 
                else {
                    Debug.logInfo("its a json object: " + key, MODULE);
                    properties.put(key, pair.getValue());
                }

        }
            document.putProperties(properties); 
        }

        catch (CouchbaseLiteException e) {
            Debug.logInfo("Error", MODULE);
            Debug.logInfo(e.getMessage(), MODULE);
        } catch (JsonProcessingException e) {
            Debug.logInfo(e.getMessage(), MODULE);
        } catch (IOException e) {
            Debug.logInfo(e.getMessage(), MODULE);
        }