Home > database >  how to convert jsonobject into jsonarray and also change all keys with all custom same keys java and
how to convert jsonobject into jsonarray and also change all keys with all custom same keys java and

Time:06-29

Code :

 Map<String, Integer> map = new LinkedHashMap<>();

                        for (int j = 0; j < jsonArray.length(); j  ) {
                            JSONObject list = jsonArray.getJSONObject(j);




                            String key = list.getString("symbol")   list.getString("groupname");


                            if (!map.containsKey(key)) {
                                map.put(key, list.getInt("openqty"));

                            } else {
                                int val = map.get(key)   list.getInt("openqty");
                                map.put(key, val);



                            }

                            System.out.println("map "  map);


                        }

                 //converted map into jsonstring
                        String jsonString = new JSONObject(map).toString();
                        System.out.println("jsonstring "   jsonString);

Output :

     {"SILVERRohit":0,"DINRCosmic":20,"NATURALGASCosmic":0,"NGCosmic":0,"SICosmic":-5,"SILVERCosmic":35,"DINRRishi":0,"SIRishi":0,"SILVERRishi":0,"CLAmitTA":-6,
"CRUDEOILAmitTA":60,"DINRAmitTA":24,"GCAmitTA":0,"GOLDAmitTA":0,"SIAmitTA":0,"SILVERAmitTA":0,"DINRPraveen":0,"GCPraveen":0,"GOLDPraveen":0,"DINRHarsh":46,
"GCHarsh":-9,"GOLDHarsh":28,"SIHarsh":9,"SILVERHarsh":-45,"DINRGovind":-160,"SIGovind":11}

^^ this is an jsonobject i have got by using linkedhashmap . So, now my problem is i want to convert it into jsonArray format to set in model (recyclerview) i have also tried by iterating but getting same values in each single row .

Not only this but also i want to change all jsonobject keys to "open" so that i can use this in recyclerview for each single row.

Expected output :

[    {"open":0},{"open":20} , {"open":0} ,   {"open":0} ,{"open":-5 } ,
{"open":35 } , {"open":0} ,{"open":0 },{"open":0 } ,{"open":-6 },
{"open":60},{"open":24},{"open":0},{"open":0},{"open":0},
{"open":0},{"open":0},{"open":0},{"open":0},{"open":46},
{"open":-9},{"open":28},{"open":9},{"open":-45},
{"open":-160},{"open":11}    ]

CodePudding user response:

as you got the hashmap ,how about iterating the map .like this

Map<String,String> data = MapUtil.newHashMap();
        JSONArray jsonArray = new JSONArray();
        for (Map.Entry<String, String> entry : data.entrySet()) {
            Map<String,String> json = MapUtil.newHashMap();
            json.put("open", entry.getValue());
            jsonArray.add(json);
        }
        return jsonArray;

  • Related