Retrieve data from complex JSON in Android Studio

-Hi, i am new to Couchbase and trying to retrieve certain portions of my JSON data which have been stored successfully into my document but to no avail. i always get a null value.

-I retrieve the properties for project_id, project_name and forms using
the document.getProperty("") method;

-But I always get “null” when i try to retrieve any other data (eg. form_name, variables) using
the document.getProperty("") method. Please help ASAP :slight_smile:

This is my JSON data being stored after being converted into hashmap using_**HashMap<String,Object> properties = new Gson().fromJson(jsonString, new TypeToken<HashMap<String, Object>>(){}.getType()).**

 {
      "project_id": "PROJ10001",
      "project_name":"Sample Project",
      "forms": [
      {
        "form_name": "main",
        "form_id": "FORM001",
        "variables": [

        {
          "id":"VAR0001",
          "variable_name": "firstname",
          "variable_label": "First Name",
          "input_type": "text",
          "hidden_text": "",
          "required": "1",
          "options": {},
          "default_value": "n/a",
          "max_length": 50,
          "min_length": 2,
          "pre_condition": "",
          "post_condition": "",
          "order_in_form": "1"
        },
        {
          "id":"VAR0002",
          "variable_name": "age",
          "variable_label": "What is your current age",
          "input_type": "number",
          "hidden_text": "",
          "required": "1",
          "options": {},
          "default_value": "0",
          "max_length": 3,
          "min_length": 2,
          "pre_condition": "",
          "post_condition": "",
          "order_in_form": "2"
        },
        { 
          "id":"VAR0003",
          "variable_name": "gender",
          "variable_label": "Gender",
          "input_type": "options",
          "hidden_text": "",
          "required": "1",
          "options": {
            "type":"list", 
            "multi":"0",
            "items":[
              {"label":"Male","value":"m", "skip":""},
              {"label":"Female","value":"f", "skip":""}
            ]
          },
          "default_value": "0",
          "max_length": 3,
          "min_length": 2,
          "pre_condition": "",
          "post_condition": "",
          "order_in_form": "3"
         }]
      },


      
      {
        "form_name": "male_form",
        "form_id": "FORM002",
        "variables": 
        [
          {
            "id":"VAR0004",
            "variable_name": "beard",
            "variable_label": "How many shirts do you have?",
            "input_type": "number",
            "hidden_text": "",
            "required": "1",
            "options": {},
            "default_value": "n/a",
            "max_length": 3,
            "min_length": 2,
            "pre_condition": "",
            "post_condition": "",
            "order_in_form": "1"
          }
      ]
    }
  ]  
}

How are you trying to access them? Show your work!

1 Like

Please this is the main code

 // Create a manager
       Manager manager = null;
       try {
           manager = new Manager(new AndroidContext(getApplicationContext()), Manager.DEFAULT_OPTIONS);
       } catch (IOException e) {
           e.printStackTrace();
       }


       // Create or open the database named test_data
       Database database = null;
       try {
           database = manager.getDatabase("test_data");
       } catch (CouchbaseLiteException e) {
           e.printStackTrace();
       }

       // Create a new document
       Document document = database.createDocument();


       //Convert JSON string to JSON object & convert to Hashmap & Store in document
       try {
           prepareCouchBase(document);
       } catch (JSONException e) {
           e.printStackTrace();
       }

   }


   }

   private void prepareCouchBase(Document document) throws JSONException {

String jsonString = " {\n" +
" \"project_id\": \"PROJ10001\",\n" +
" \"project_name\":\"Sample Project\",\n" +
" \"forms\": [\n" +
" {\n" +
" \"form_name\": \"main\",\n" +
" \"form_id\": \"FORM001\",\n" +
" \"variables\": [\n" +
" \n" +
" {\n" +
" \"id\":\"VAR0003\",\n" +
" \"variable_name\": \"gender\",\n" +
" \"variable_label\": \"Gender\",\n" +
" \"input_type\": \"options\",\n" +
" \"hidden_text\": \"\",\n" +
" \"required\": \"1\",\n" +
" \"options\": {\n" +
" \"type\":\"list\", \n" +
" \"multi\":\"0\",\n" +
" \"items\":[\n" +
" {\"label\":\"Male\",\"value\":\"m\", \"skip\":\"\"},\n" +
" {\"label\":\"Female\",\"value\":\"f\", \"skip\":\"\"}\n" +
" ]\n" +
" },\n" +
" \"default_value\": \"0\",\n" +
" \"max_length\": 3,\n" +
" \"min_length\": 2,\n" +
" \"pre_condition\": \"\",\n" +
" \"post_condition\": \"\",\n" +
" \"order_in_form\": \"3\"\n" +
" }]\n" +
" }\n" +
" ] \n" +
" }";

    //Convert JSON string to JSON Object
       JSONObject jsonObject = null;
       try {
            jsonObject = new JSONObject(jsonString);
       } catch (JSONException e) {
           e.printStackTrace();
       }


       //Convert JSON to Hashmap
       try {
           HashMap<String,Object> properties = new Gson().fromJson(String.valueOf(jsonObject), new TypeToken<HashMap<String, Object>>(){}.getType());

           //Store JSON object into document
           document.putProperties(properties);

           //Log output
           Log.d("test_data", String.format("Document ID :: %s", document.getId()));
           Log.d("test_data", String.format("Document Properties :: %s", document.getProperties()));
           Log.d("test_data", String.format("Project ID - "+  document.getProperty("project_id")+ " & Project Name- "+ document.getProperty("project_name")));
           Log.d("test_data", "forms ::"+ document.getProperty("forms"));

       } catch (CouchbaseLiteException e) {
           e.printStackTrace();
       }

       Toast.makeText(this, document.getProperty("forms")+"", Toast.LENGTH_LONG).show();

   }

Please any feedback?

I’m having trouble remembering the way it was in 1.x because it’s been a while but I believe you cannot access subproperties of properties directly through the document. You need to get the top level property first as a dictionary (forms) and then access its sub-property (form_name). Since you didn’t show what you did to get the sub-property I am not sure if you are doing this or not.

Any idea of how to access their sub-properties? or a tutorial to assist me?

Also am I getting the top level property as a dictionary form, as you have clearly posted?

What I mean is get forms out as a dictionary, and then access the form_name key of that dictionary.

1 Like

Please help with some code. I think I am doing what you are saying. Please help

Maybe I am using the wrong term. I am not a Java developer.

The result of document.getProperty("forms") is what I would call a dictionary. I guess it’s a HashMap in Java. Inside this HashMap should be a key called form_name. Is that not the case?

You have said it rightly, there is a key called form_name, but accessing it and other sub-properties is the problem

What happens when you try? You cannot access these properties directly via getProperty. You need to first extract the forms HashMap, and then from that HashMap extract the property you want (e.g. form_name). Something like this.

// Don't know the exact Java syntax 
forms = document.getProperty("forms") as HashMap<String, Object>; 
form_name = forms.get("form_name") as String;

EDIT

Sorry, looking at the JSON again forms is an array.

// Don't know the exact Java syntax 
forms = document.getProperty("forms") as ArrayList<Object>; 
firstForm = forms.get(0) as HashMap<String, Object>; ;
form_name = firstForm.get("form_name") as String;

This seems to be a good reference. Thanks

I’m able to retrieve all the data except that of options,
Getting this error when trying to get data from the options key

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to java.util.ArrayList

This the code i use to get all the other properties

 forms = (ArrayList<Object>) document.getProperty("forms");
 firstForm = (HashMap<String, Object>) forms.get(0);
 variables = (ArrayList<Object>) firstForm.get("variables");
 sub_variables = (HashMap<String,Object>) variables.get(0);

And this is for retrieving that of options

 options = (ArrayList<Object>) sub_variables.get("options");

That’s because your options is not an array ([]), it is a hashmap ({}).