Mavericks
Mavericks

Reputation: 283

Convert Nested JSONObject to JSONArray and then PUT it into HashMap in java

I've a JSON,

{
  "result": {
    "issue_date": "30-05-2003",
    "father/husband": "TEST",
    "name": "ABC ",
    "blood_group": "",
    "dob": "23-03-1912",
    "validity": {
      "non-transport": "11-12-2012 to 10-12-2032",
      "transport": "11-12-2012 to 10-12-2015"
    },
    "cov_details": {
      "MCWG": "NA",
      "3WTR": "NA",
      "PSV BUS": "NA",
      "LMV": "NA",
      "INVCRG": "NA"
    },
    "address": "ABCD"
  }
}

Now I am reading the values of cov_details, using

cov = jsonObject.getJSONObject("result").getJSONObject("cov_details").getString("LMV");

        if(cov != null) {
            cov="LMV";
            dlCovs.put("class_of_vehicle", cov);
        }
        else{
            dlCovs.put("class_of_vehicle","");
        }
        cov1 = jsonObject.getJSONObject("result").getJSONObject("cov_details").getString("MCWG");
        if(cov1 != null){
            cov1 ="MCWG";
            dlCovs.put("class_of_vehicle", cov1);
        }

in JSONObject and mapping the every value like above mentioned code, now my problem is i'm hard coding the Value based on the String that i'm getting (LMV,MCWG) but their is a possibility that their could be several more values within COV_DETAILS, so all i want is to store these every value into on an Object so that i can iterate over these values in order to get it printed on the front end.

Upvotes: 0

Views: 626

Answers (1)

Jaymin Panchal
Jaymin Panchal

Reputation: 2856

You can iterate over your json keys getting in cov_details object.

Iterator<?> keys = jsonObject.getJSONObject("result").getJSONObject("cov_details").keys();

while( keys.hasNext() ) {
   String key = (String)keys.next();
   String value= jObject.get(key);
   //do whatever you want to do
}

Upvotes: 1

Related Questions