0

I have this Json:

{
  "withDrawAccountNumber": "1.10.100.1",
  "Amount": "1000",
  "creditor": {
    "2.20.200.2": "1700",
    "2.20.200.1": "300"
  }
}

i want to get the creditor's key value in HashMap, output must be like this:

"2.20.200.2": "1700",
"2.20.200.1": "300"

i dont have any idea how i must do this.

Sajjad Serajzadeh
  • 334
  • 1
  • 3
  • 13
  • 1
    Welcome to Stack Overflow! You seem to be asking for someone to write some code for you. Stack Overflow is a question and answer site, not a code-writing service. Please [see here](https://stackoverflow.com/help/how-to-ask) to learn how to write effective questions – azro May 30 '21 at 10:27
  • See https://stackoverflow.com/questions/443499/convert-json-to-map – azro May 30 '21 at 10:27

3 Answers3

1
Gson gson = new Gson();
Map map = gson.fromJson(jsonData, Map.class);
Asif
  • 354
  • 3
  • 12
1

why not use this :

    Map<String,String> testMap = new HashMap<String, String>();
        String testJson = "{\r\n"
                + "  \"withDrawAccountNumber\": \"1.10.100.1\",\r\n"
                + "  \"Amount\": \"1000\",\r\n"
                + "  \"creditor\": {\r\n"
                + "    \"2.20.200.2\": \"1700\",\r\n"
                + "    \"2.20.200.1\": \"300\"\r\n"
                + "  }\r\n"
                + "}";
        
        JSONObject ob = new JSONObject(testJson);
        JSONObject cr = ob.getJSONObject("creditor");
        Set<String> keys = cr.keySet();
        for(String key : keys) {
            testMap.put(key, cr.getString(key));
        }
        
        testMap.forEach((K,V)->System.out.println("key : "+K+" Value : "+V));
Abhishek
  • 423
  • 6
  • 12
0

I dont really see the purpose on why you would do that, but you could do something like this i guess:

JSONObject jsonObj = new JSONObject(obj);
HashMap<String,String> map = new HashMap<String,String>();

String value = jsonObj.getString("2.20.2001");
map.put("2.20.2001", value);
// ... use map here in what you want to achieve