244

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?

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
David Santamaria
  • 8,671
  • 7
  • 33
  • 43
  • 3
    I have written code for this without using any library. http://stackoverflow.com/questions/21720759/jsonobject-to-map/24012023#24012023 – Vikas Gupta Oct 31 '14 at 09:43

19 Answers19

433

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)

Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
StaxMan
  • 113,358
  • 34
  • 211
  • 239
  • 53
    Moreover, if you want a typed Map (exploiting java generics), you can do : Map typedMap = mapper.readValue(jsonStream, new TypeReference>() {}); – obe6 Dec 29 '14 at 20:46
  • 5
    If you work with Maven project, you will need com.fasterxml.jackson.core jackson-databind 2.4.4 – LoBo Nov 02 '15 at 09:49
  • 2
    And looks like Jackson has moved since 09 so: [Jackson data-bind](https://github.com/FasterXML/jackson-databind/#1-minute-tutorial-pojos-to-json-and-back) – jacob.mccrumb Sep 21 '16 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 '18 at 09:39
  • 1
    FWTW, while @obe6's answer is technically correct, you can use shorter form too: `Map result = mapper.readValue(source, Map.class)`. – StaxMan Nov 28 '18 at 06:40
48

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);
Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181
David L
  • 497
  • 4
  • 2
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();
bugs_
  • 3,544
  • 4
  • 34
  • 39
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));

}
El Marce
  • 3,144
  • 1
  • 26
  • 40
j.d.
  • 199
  • 1
  • 2
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 !

Jad B.
  • 1,403
  • 15
  • 14
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.

isapir
  • 21,295
  • 13
  • 115
  • 116
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);
    }
}
Pavan
  • 140
  • 3
  • 10
  • I tried this approach buts its not working ... can you answer for this? https://stackoverflow.com/questions/60329223/how-to-update-existing-json-file-in-java/60329607#60329607 – Siva Feb 26 '20 at 16:22
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>
Fabio Araujo
  • 131
  • 3
  • 7
4
java.lang.reflect.Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
Gson gson = new Gson();
Map<String, Object> categoryicons = gson.fromJson(json, mapType );
newMaziar
  • 41
  • 1
4

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

Map<String, Object> myMap = myJsonObject.toMap();
Omri Levi
  • 177
  • 5
3

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

Bruno Ranschaert
  • 7,428
  • 5
  • 36
  • 46
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.

pcjuzer
  • 2,724
  • 4
  • 25
  • 34
  • I get `null` back from a simple JSON string where one of the values is an array of strings. – isapir Sep 12 '16 at 05: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;
}
somtomas
  • 163
  • 1
  • 2
  • 6
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

Kumar Gaurav
  • 15
  • 1
  • 5
1

Try this piece of code, it worked for me,

Map<String, Object> retMap = new Gson().fromJson(
                myJsonString, new TypeToken<HashMap<String, Object>>() {}.getType()
        );
Mani
  • 3,394
  • 3
  • 30
  • 36
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}
    }
}
Valentyn Kolesnikov
  • 2,029
  • 1
  • 24
  • 31
0
import net.sf.json.JSONObject

JSONObject.fromObject(yourJsonString).toMap
renzherl
  • 161
  • 1
  • 3
-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.