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.

2
  • 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 to learn how to write effective questions Commented May 30, 2021 at 10:27
  • See stackoverflow.com/questions/443499/convert-json-to-map Commented May 30, 2021 at 10:27

3 Answers 3

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));
Sign up to request clarification or add additional context in comments.

Comments

1
Gson gson = new Gson();
Map map = gson.fromJson(jsonData, Map.class);

Comments

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

2 Comments

there is not specific number of creditors values: at least one must be there. and the keys can be difference
stackoverflow.com/questions/443499/convert-json-to-map as azro commented 30 minutes ago, is the best way to go as it seems :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.