Convert JSON to Map

2019-01-01 05:43发布

问题:

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:

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, http://wiki.fasterxml.com/JacksonInFiveMinutes), you\'d do:

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

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



回答2:

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();


回答3:

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);


回答4:

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));

}


回答5:

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:

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>


回答7:

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);
    }
}


回答8:

java.lang.reflect.Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
Gson gson = new Gson();
Map<String, Object> categoryicons = gson.fromJson(json, mapType );


回答9:

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.



回答10:

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



回答11:

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.



回答12:

import net.sf.json.JSONObject

JSONObject.fromObject(yourJsonString).toMap


回答13:

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

Code example:

import com.github.underscore.lodash.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}
    }
}


回答14:

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.