1

I'm using Java.

I have a JSON string like this given below :

{  
    "4562": {  
        "a":       "foo1",   
        "b":      "56",   
        "c":    "1342" 
    },
    "4563": {  
        "a":       "foo2",   
        "b":      "57",   
        "c":    "1343" 
    }
}

I want to store all the data from the JSON string into Map.

How to do that ?

2 Answers 2

1

You need to use Jackson Library (jackson-databind).

Code :

import java.io.IOException;
import java.util.Map;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Example {

    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        String inputJson = "{  \n" + 
                "    \"4562\": {  \n" + 
                "        \"a\":       \"foo1\",   \n" + 
                "        \"b\":      \"56\",   \n" + 
                "        \"c\":    \"1342\" \n" + 
                "    },\n" + 
                "    \"4563\": {  \n" + 
                "        \"a\":       \"foo2\",   \n" + 
                "        \"b\":      \"57\",   \n" + 
                "        \"c\":    \"1343\" \n" + 
                "    }\n" + 
                "}";
         Map<String, Map<String, String>> map = mapper.readValue(inputJson, Map.class);
         System.out.println(map);

    }

}

Output :

{4562={a=foo1, b=56, c=1342}, 4563={a=foo2, b=57, c=1343}}

Download jar from here : https://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-databind/2.10.1/

Sign up to request clarification or add additional context in comments.

2 Comments

@preethamreddy Is this helpful ?
Thank you for the reply!, yes it is !!
1

Use Gson:

String json = ...;
Gson gson = new GsonBuilder.setPrettyPrinting().create();
Map<String, Map<String, String>> map = gson.<Map<String, Map<String, String>>>fromJson(json, Map.class);
System.out.println(map);

3 Comments

I'm not sure this does what they want. With this, the values will be Strings, while from the JSON structure it seems that the values should be Maps. Granted, it's not very clear from the question which one is correct.
@a.deshpande012 you are right. It does appear to be a have map values.
Thank you for the reply!, i think i found my answer

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.