247

What is the best way to convert a JSON code as this:

{ 
    "data" : 
    { 
        "field1" : "value1", 
        "field2" : "value2"
    }
}

in a Java Map in which one the keys are (field1, field2) and the values for those fields are (value1, value2).

Any ideas? Should I use Json-lib for that? Or better if I write my own parser?

1

19 Answers 19

441

I hope you were joking about writing your own parser. :-)

For such a simple mapping, most tools from http://json.org (section java) would work. For one of them (Jackson https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator), you'd do:

Map<String,Object> result =
        new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);

(where JSON_SOURCE is a File, input stream, reader, or json content String)

5
  • 53
    Moreover, if you want a typed Map (exploiting java generics), you can do : Map<String, MyPojo> typedMap = mapper.readValue(jsonStream, new TypeReference<Map<String, MyPojo>>() {});
    – obe6
    Dec 29, 2014 at 20:46
  • 5
    If you work with Maven project, you will need <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.4.4</version> </dependency>
    – LoBo
    Nov 2, 2015 at 9:49
  • 2
    And looks like Jackson has moved since 09 so: Jackson data-bind Sep 21, 2016 at 18:42
  • 1
    @obe6 I guess the OP is not joking. Can you find a single "JSON" anywhere in your code snippet other than that arbitrary variable name? I'm struggling too because of the names in Jackson API.
    – Aetherus
    Nov 22, 2018 at 9:39
  • 1
    FWTW, while @obe6's answer is technically correct, you can use shorter form too: Map<String,Object> result = mapper.readValue(source, Map.class).
    – StaxMan
    Nov 28, 2018 at 6:40
49

Using the GSON library:

import com.google.gson.Gson;
import com.google.common.reflect.TypeToken;
import java.lang.reclect.Type;

Use the following code:

Type mapType = new TypeToken<Map<String, Map>>(){}.getType();  
Map<String, String[]> son = new Gson().fromJson(easyString, mapType);
2
  • 13
    java at its best: TypeToken<Map<String, Map>> :-)
    – froderik
    Oct 26, 2014 at 8:10
  • 5
    With new TypeToken<Map<String, Object>> it will work also when there are arrays inside. Jan 10, 2018 at 13:19
37

I like google gson library.
When you don't know structure of json. You can use

JsonElement root = new JsonParser().parse(jsonString);

and then you can work with json. e.g. how to get "value1" from your gson:

String value1 = root.getAsJsonObject().get("data").getAsJsonObject().get("field1").getAsString();
2
  • 19
    This can throw NullPointerExceptions 5 different ways if you get unexpected data.
    – dfraser
    Aug 27, 2015 at 14:31
  • You can use .path() now and it won't throw a NPE
    – Beez
    Mar 9, 2020 at 21:41
19

Use JSON lib E.g. http://www.json.org/java/

// Assume you have a Map<String, String> in JSONObject jdata
@SuppressWarnings("unchecked")
Iterator<String> nameItr = jdata.keys();
Map<String, String> outMap = new HashMap<String, String>();
while(nameItr.hasNext()) {
    String name = nameItr.next();
    outMap.put(name, jdata.getString(name));

}
15

My post could be helpful for others, so imagine you have a map with a specific object in values, something like that:

{  
   "shopping_list":{  
      "996386":{  
         "id":996386,
         "label":"My 1st shopping list",
         "current":true,
         "nb_reference":6
      },
      "888540":{  
         "id":888540,
         "label":"My 2nd shopping list",
         "current":false,
         "nb_reference":2
      }
   }
}

To parse this JSON file with GSON library, it's easy : if your project is mavenized

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.3.1</version>
</dependency>

Then use this snippet :

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

//Read the JSON file
JsonElement root = new JsonParser().parse(new FileReader("/path/to/the/json/file/in/your/file/system.json"));

//Get the content of the first map
JsonObject object = root.getAsJsonObject().get("shopping_list").getAsJsonObject();

//Iterate over this map
Gson gson = new Gson();
for (Entry<String, JsonElement> entry : object.entrySet()) {
    ShoppingList shoppingList = gson.fromJson(entry.getValue(), ShoppingList.class);
    System.out.println(shoppingList.getLabel());
}

The corresponding POJO should be something like that :

public class ShoppingList {

    int id;

    String label;

    boolean current;

    int nb_reference;

    //Setters & Getters !!!!!
}

Hope it helps !

6

With google's Gson 2.7 (probably earlier versions too, but I tested 2.7) it's as simple as:

Map map = gson.fromJson(json, Map.class);

Which returns a Map of type class com.google.gson.internal.LinkedTreeMap and works recursively on nested objects.

6

I do it this way. It's Simple.

import java.util.Map;
import org.json.JSONObject;
import com.google.gson.Gson;

public class Main {
    public static void main(String[] args) {
        JSONObject jsonObj = new JSONObject("{ \"f1\":\"v1\"}");
        @SuppressWarnings("unchecked")
        Map<String, String> map = new Gson().fromJson(jsonObj.toString(),Map.class);
        System.out.println(map);
    }
}
1
5

This way its works like a Map...

JSONObject fieldsJson = new JSONObject(json);
String value = fieldsJson.getString(key);

<dependency>
    <groupId>org.codehaus.jettison</groupId>
    <artifactId>jettison</artifactId>
    <version>1.1</version>
</dependency>
3
  • 1
    Yes, but you must wrap every single ´get´ in try/catch because of JSON exceptions. Oct 28, 2013 at 9:28
  • 1
    you could write a class, JsonMap implements Map<String,Object to wrap JSONObject. then you get the true Map interface. Jan 16, 2014 at 18:54
  • Please add used libraries.
    – mvermand
    Jan 22, 2018 at 6:56
4
java.lang.reflect.Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
Gson gson = new Gson();
Map<String, Object> categoryicons = gson.fromJson(json, mapType );
4

If you're using org.json, JSONObject has a method toMap(). You can easily do:

Map<String, Object> myMap = myJsonObject.toMap();
3

The JsonTools library is very complete. It can be found at Github.

0
3

Try this code:

  public static Map<String, Object> convertJsonIntoMap(String jsonFile) {
        Map<String, Object> map = new HashMap<>();
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
            mapper.readValue(jsonFile, new TypeReference<Map<String, Object>>() {
            });
            map = mapper.readValue(jsonFile, new TypeReference<Map<String, String>>() {
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
2

One more alternative is json-simple which can be found in Maven Central:

(JSONObject)JSONValue.parse(someString); //JSONObject is actually a Map.

The artifact is 24kbytes, doesn't have other runtime dependencies.

1
  • I get null back from a simple JSON string where one of the values is an array of strings.
    – isapir
    Sep 12, 2016 at 5:45
1

If you need pure Java without any dependencies, you can use build in Nashorn API from Java 8. It is deprecated in Java 11.

This is working for me:

...
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
...

public class JsonUtils {

    public static Map parseJSON(String json) throws ScriptException {
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine engine = sem.getEngineByName("javascript");

        String script = "Java.asJSONCompatible(" + json + ")";

        Object result = engine.eval(script);

        return (Map) result;
    }
}

Sample usage

JSON:

{
    "data":[
        {"id":1,"username":"bruce"},
        {"id":2,"username":"clark"},
        {"id":3,"username":"diana"}
    ]
}

Code:

...
import jdk.nashorn.internal.runtime.JSONListAdapter;
...

public static List<String> getUsernamesFromJson(Map json) {
    List<String> result = new LinkedList<>();

    JSONListAdapter data = (JSONListAdapter) json.get("data");

    for(Object obj : data) {
        Map map = (Map) obj;
        result.add((String) map.get("username"));
    }

    return result;
}
1

JSON to Map always gonna be a string/object data type. i have GSON lib from google. Gson library working with string not for complex objects you need to do something else

1

Try this piece of code, it worked for me,

Map<String, Object> retMap = new Gson().fromJson(
                myJsonString, new TypeToken<HashMap<String, Object>>() {}.getType()
        );
0
import net.sf.json.JSONObject

JSONObject.fromObject(yourJsonString).toMap
0

Underscore-java library can convert json string to hash map. I am the maintainer of the project.

Code example:

import com.github.underscore.U;
import java.util.*;

public class Main {

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        String json = "{"
            + "    \"data\" :"
            + "    {"
            + "        \"field1\" : \"value1\","
            + "        \"field2\" : \"value2\""
            + "    }"
            + "}";

       Map<String, Object> data = (Map) U.get((Map<String, Object>) U.fromJson(json), "data");
       System.out.println(data);

       // {field1=value1, field2=value2}
    }
}
0
-1

JSON to Map always gonna be a string/object data type. i haved GSON lib from google.

works very well and JDK 1.5 is the min requirement.

1
  • 1
    How did you use GSON?
    – NinjaCoder
    Jun 8, 2015 at 20:08

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.