Search code examples
javajsonjacksoncouchbasecouchbase-lite

create JAVA Map out of JSON file using Jackson libraries


I am using CouchbaseLite to build embedded database of NoSQL type. Downloaded libraries for 1.3 version couchbase-lite-java-1.3.1-community.zip and added them to my Java project in eclipse.

Following are the tasks I want to achieve?

  1. Read .json file (let us assume the file path J:/temp/sample.json)
  2. Convert it to Map
  3. Insert into CouchBase database.

Following is the code that I tried:

    CouchDBManager dbManager = new CouchDBManager();
    Database myDB = dbManager.createDataBase("atempt1");
    // first step
    File f = new File("J:/temp/sample.json");
    // code to read the content of a file
    // second step
    ObjectNode objectNode1 = mapper.createObjectNode();
    // add code to covert the json content read from the file to Map
    // third step
    Document doc = myDB.createDocument();
    doc.putProperties(map); // putProperties expectes Map object

So, kindly help me in reading the json file and convert it to Map using Jackson libraries so that I can create and insert the document into CouchbaseLite DB.

Note: Jackson libraries are part of CouchBaseLite that I downloaded, so I want a solution around it. I don't want to use custom processing of JSON file and convert it to Map, which is error prone and performance issue.


Solution

  • Please have a look at Jackson data bind docs int the below link:

    map = mapper.readValue(new File("J:/temp/sample.json"), HashMap.class);
    

    returns a Map.

    Reference:

    1. http://fasterxml.github.io/jackson-databind/javadoc/2.5/com/fasterxml/jackson/databind/ObjectMapper.html#readValue(java.io.File,%20com.fasterxml.jackson.databind.JavaType)