Gurumoorthy Arumugam
Gurumoorthy Arumugam

Reputation: 2128

How to insert data in couchbase lite android in JSON format

I'm new to NoSQL databases. I want to save the following JSON data into CouchBase Lite. Can someone guide me on the best way to do this?

{"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;"
    }
}}    

I tried to do this using the following code.

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);
    }
}

But this code is creating a new id each time. I want to insert the same widget value in multiple times.

This is run time data, not static data I want to insert one by one.

For example, given a widget Map as follows:

{"widget": {

        "window": {
            "title": "Sample Konfabulator Widget",
            "name": "main_window",
            "width": 500,
            "height": 500
        },
}

then I want to append the following field under the "window" field:

 "image": { 
            "src": "Images/Sun.png",
            "name": "sun1",
            "hOffset": 250,
            "vOffset": 250,
            "alignment": "center"
        },
}

Upvotes: 2

Views: 2296

Answers (4)

JoCuTo
JoCuTo

Reputation: 2483

There is a very useful link where you can find good info https://blog.couchbase.com/object-mapping-couchbase-mobile-android/

Upvotes: 0

Web Development
Web Development

Reputation: 421

I was having the same problem. You need to traverse the keys of the json and add each object using putproperties. However, for a JSONArray, you need to use an ArrayList. I am traversing the keys using the Jackson library(which is also used by couchbase internally)

        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);
        }

Upvotes: 0

jamiltz
jamiltz

Reputation: 1144

The constraint on documents in Couchbase Lite is that the _id property should be unique. As the document gets updated, it creates new revisions.

There are two possible methods to update a document:

  • putProperties: given a new JSON object, it replaces the document's body with that object.
  • update: takes a callback function or block. It loads the current revision's properties, then calls this function, passing it an UnsavedRevision object, whose, properties are a mutable copy of the current ones. Your callback code can modify this object's properties as it sees fit; after it returns, the modified revision is saved and becomes the current one.

So, to update a widget document with the image dictionary, you should use the update method:

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;
    }
});

Note: It's recommended to use a library like Jackson to serialize/deserialize the JSON and POJO models in a Java application (you can read this blog post to find more info).

Upvotes: 1

pushpendra chauhan
pushpendra chauhan

Reputation: 2375

You need to construct your map like this to save like above json format.

 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);
    }

Upvotes: 0

Related Questions