0

I tried few days to get this done. but could`t .

What i want is Traverse any given JSON and put Key and Value pair into a map. As a sample consider this JSON

 String test = {
   "RechargeRequest":{
      "RechargeSerialNo":"2645",
      "RechargeChannelID":"3",
      "RechargeObj":{
         "SubAccessCode":{
            "PrimaryIdentity":"763500001"
         }
      },
      "RechargeInfo":{
         "CashPayment":[
            {
               "Amount":"30"
            }
         ]
      }
   }
}

What i have tried so far

JSONObject jsonObj = new JSONObject(test);
    Iterator<String> keys = jsonObj.keys();
    Map<String,String> map = new HashMap<>();
    while(keys.hasNext()) {
        String key = keys.next();
        if (jsonObj.get(key) instanceof JSONObject) {

        }else if(jsonObj.get(key) instanceof  JSONArray){

        }else{

        }
    }

Maps value should be like ( "RechargeChannelID","3") ( "Amount":"30")

Can anybody help me please?

Thanks,

Das_J
  • 71
  • 2
  • 9
  • what happens for jsonArray as there could be multiple same key in array so as values ? And in that case, setting values to map will definitely override previous value – user404 Dec 12 '19 at 11:51
  • btw, what is problem in your approach? it seems ok though... additionally, you have to do your task recursively inside your `if-else` condition as they may contain nested object. You can write another method and pass the `JSONObject` or `JSONArray Object` whatever you find to get its all nested key-pairs. But you have to consider my first comment for array elements though – user404 Dec 12 '19 at 12:02
  • Why did you want to do this? Because the same key may appears in a JSON array or other JOSN node with different levels. – LHCHIN Dec 13 '19 at 01:04
  • Possible duplicate of [Flatten a JSON string to Map using Gson or Jackson](https://stackoverflow.com/questions/29759462/flatten-a-json-string-to-mapstring-string-using-gson-or-jackson). – LHCHIN Dec 13 '19 at 05:20

1 Answers1

1

If I understood correctly you want to flatten your json file into one level then map it to key and value pairs, kindly check the link below: How to deserialize JSON into flat, Map-like structure?

Anas Ablan
  • 56
  • 3
  • No i want to go through a map and put the each key and value into that map and modify some values in the map – Das_J Dec 12 '19 at 11:07