将JSONstring转换为HashMap

我使用的是Java,而且我有一个JSONstring:

{ "name" : "abc" , "email id " : ["abc@gmail.com","def@gmail.com","ghi@gmail.com"] } 

我有一个在Java地图:

 Map<String, Object> retMap = new HashMap<String, Object>(); 

我想将所有来自JSONObject的数据存储在该HashMap中。

任何人都可以提供这样的代码? 我想使用'org.json'库。

几天前我通过recursion来编写这段代码。

 public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException { Map<String, Object> retMap = new HashMap<String, Object>(); if(json != JSONObject.NULL) { retMap = toMap(json); } return retMap; } public static Map<String, Object> toMap(JSONObject object) throws JSONException { Map<String, Object> map = new HashMap<String, Object>(); Iterator<String> keysItr = object.keys(); while(keysItr.hasNext()) { String key = keysItr.next(); Object value = object.get(key); if(value instanceof JSONArray) { value = toList((JSONArray) value); } else if(value instanceof JSONObject) { value = toMap((JSONObject) value); } map.put(key, value); } return map; } public static List<Object> toList(JSONArray array) throws JSONException { List<Object> list = new ArrayList<Object>(); for(int i = 0; i < array.length(); i++) { Object value = array.get(i); if(value instanceof JSONArray) { value = toList((JSONArray) value); } else if(value instanceof JSONObject) { value = toMap((JSONObject) value); } list.add(value); } return list; } 

使用GSon ,您可以执行以下操作:

 Map<String, Object> retMap = new Gson().fromJson( jsonString, new TypeToken<HashMap<String, Object>>() {}.getType() ); 

Vikas的代码移植到JSR 353:

 import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.json.JsonArray; import javax.json.JsonException; import javax.json.JsonObject; public class JsonUtils { public static Map<String, Object> jsonToMap(JsonObject json) { Map<String, Object> retMap = new HashMap<String, Object>(); if(json != JsonObject.NULL) { retMap = toMap(json); } return retMap; } public static Map<String, Object> toMap(JsonObject object) throws JsonException { Map<String, Object> map = new HashMap<String, Object>(); Iterator<String> keysItr = object.keySet().iterator(); while(keysItr.hasNext()) { String key = keysItr.next(); Object value = object.get(key); if(value instanceof JsonArray) { value = toList((JsonArray) value); } else if(value instanceof JsonObject) { value = toMap((JsonObject) value); } map.put(key, value); } return map; } public static List<Object> toList(JsonArray array) { List<Object> list = new ArrayList<Object>(); for(int i = 0; i < array.size(); i++) { Object value = array.get(i); if(value instanceof JsonArray) { value = toList((JsonArray) value); } else if(value instanceof JsonObject) { value = toMap((JsonObject) value); } list.add(value); } return list; } } 

将JSONstring转换为映射

 public static Map<String, Object> jsonString2Map( String jsonString ) throws JSONException{ Map<String, Object> keys = new HashMap<String, Object>(); org.json.JSONObject jsonObject = new org.json.JSONObject( jsonString ); // HashMap Iterator<?> keyset = jsonObject.keys(); // HM while (keyset.hasNext()) { String key = (String) keyset.next(); Object value = jsonObject.get(key); System.out.print("\n Key : "+key); if ( value instanceof org.json.JSONObject ) { System.out.println("Incomin value is of JSONObject : "); keys.put( key, jsonString2Map( value.toString() )); }else if ( value instanceof org.json.JSONArray) { org.json.JSONArray jsonArray = jsonObject.getJSONArray(key); //JSONArray jsonArray = new JSONArray(value.toString()); keys.put( key, jsonArray2List( jsonArray )); } else { keyNode( value); keys.put( key, value ); } } return keys; } 

将JSON数组转换为列表

 public static List<Object> jsonArray2List( JSONArray arrayOFKeys ) throws JSONException{ System.out.println("Incoming value is of JSONArray : ========="); List<Object> array2List = new ArrayList<Object>(); for ( int i = 0; i < arrayOFKeys.length(); i++ ) { if ( arrayOFKeys.opt(i) instanceof JSONObject ) { Map<String, Object> subObj2Map = jsonString2Map(arrayOFKeys.opt(i).toString()); array2List.add(subObj2Map); }else if ( arrayOFKeys.opt(i) instanceof JSONArray ) { List<Object> subarray2List = jsonArray2List((JSONArray) arrayOFKeys.opt(i)); array2List.add(subarray2List); }else { keyNode( arrayOFKeys.opt(i) ); array2List.add( arrayOFKeys.opt(i) ); } } return array2List; } 

显示任何格式的JSON

 public static void displayJSONMAP( Map<String, Object> allKeys ) throws Exception{ Set<String> keyset = allKeys.keySet(); // HM$keyset if (! keyset.isEmpty()) { Iterator<String> keys = keyset.iterator(); // HM$keysIterator while (keys.hasNext()) { String key = keys.next(); Object value = allKeys.get( key ); if ( value instanceof Map ) { System.out.println("\n Object Key : "+key); displayJSONMAP(jsonString2Map(value.toString())); }else if ( value instanceof List ) { System.out.println("\n Array Key : "+key); JSONArray jsonArray = new JSONArray(value.toString()); jsonArray2List(jsonArray); }else { System.out.println("key : "+key+" value : "+value); } } } } 

Google.gson到HashMap。

 import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class JsonUtils { public static Map<String, Object> jsonToMap(JSONObject json) { Map<String, Object> retMap = new HashMap<String, Object>(); if(json != null) { retMap = toMap(json); } return retMap; } public static Map<String, Object> toMap(JSONObject object) { Map<String, Object> map = new HashMap<String, Object>(); Iterator<String> keysItr = object.keySet().iterator(); while(keysItr.hasNext()) { String key = keysItr.next(); Object value = object.get(key); if(value instanceof JSONArray) { value = toList((JSONArray) value); } else if(value instanceof JSONObject) { value = toMap((JSONObject) value); } map.put(key, value); } return map; } public static List<Object> toList(JSONArray array) { List<Object> list = new ArrayList<Object>(); for(int i = 0; i < array.size(); i++) { Object value = array.get(i); if(value instanceof JSONArray) { value = toList((JSONArray) value); } else if(value instanceof JSONObject) { value = toMap((JSONObject) value); } list.add(value); } return list; } } 

希望这会工作,试试这个:

 import com.fasterxml.jackson.databind.ObjectMapper; Map<String, Object> response = new ObjectMapper().readValue(str, HashMap.class); 

str,你的JSONstring

像这样简单,如果你想要emailid,

 String emailIds = response.get("email id").toString(); 

你可以使用谷歌的GSON库来转换JSON对象。

https://code.google.com/p/google-gson/

其他图书馆如jackson也可用。

这不会将其转换为地图。 但是你可以做所有你想做的事情。

您可以使用Jackson库将任何JSON转换为map ,如下所示:

 String json = "{\r\n\"name\" : \"abc\" ,\r\n\"email id \" : [\"abc@gmail.com\",\"def@gmail.com\",\"ghi@gmail.com\"]\r\n}"; ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = new HashMap<String, Object>(); // convert JSON string to Map map = mapper.readValue(json, new TypeReference<Map<String, Object>>() {}); System.out.println(map); 

jackson的 Maven依赖关系:

 <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.5.3</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.3</version> <scope>compile</scope> </dependency> 

希望这会有所帮助。 快乐编码:)

以下parsing器使用Google的JsonParser.parse方法读取文件,将其parsing为通用JsonElement ,然后将生成的JSON中的所有项目转换为本机Java List<object>Map<String, Object>

注意 :下面的代码是基于Vikas Gupta的答案 。

GsonParser.java

 import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; public class GsonParser { public static void main(String[] args) { try { print(loadJsonArray("data_array.json", true)); print(loadJsonObject("data_object.json", true)); } catch (Exception e) { e.printStackTrace(); } } public static void print(Object object) { System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(object).toString()); } public static Map<String, Object> loadJsonObject(String filename, boolean isResource) throws UnsupportedEncodingException, FileNotFoundException, JsonIOException, JsonSyntaxException, MalformedURLException { return jsonToMap(loadJson(filename, isResource).getAsJsonObject()); } public static List<Object> loadJsonArray(String filename, boolean isResource) throws UnsupportedEncodingException, FileNotFoundException, JsonIOException, JsonSyntaxException, MalformedURLException { return jsonToList(loadJson(filename, isResource).getAsJsonArray()); } private static JsonElement loadJson(String filename, boolean isResource) throws UnsupportedEncodingException, FileNotFoundException, JsonIOException, JsonSyntaxException, MalformedURLException { return new JsonParser().parse(new InputStreamReader(FileLoader.openInputStream(filename, isResource), "UTF-8")); } public static Object parse(JsonElement json) { if (json.isJsonObject()) { return jsonToMap((JsonObject) json); } else if (json.isJsonArray()) { return jsonToList((JsonArray) json); } return null; } public static Map<String, Object> jsonToMap(JsonObject jsonObject) { if (jsonObject.isJsonNull()) { return new HashMap<String, Object>(); } return toMap(jsonObject); } public static List<Object> jsonToList(JsonArray jsonArray) { if (jsonArray.isJsonNull()) { return new ArrayList<Object>(); } return toList(jsonArray); } private static final Map<String, Object> toMap(JsonObject object) { Map<String, Object> map = new HashMap<String, Object>(); for (Entry<String, JsonElement> pair : object.entrySet()) { map.put(pair.getKey(), toValue(pair.getValue())); } return map; } private static final List<Object> toList(JsonArray array) { List<Object> list = new ArrayList<Object>(); for (JsonElement element : array) { list.add(toValue(element)); } return list; } private static final Object toPrimitive(JsonPrimitive value) { if (value.isBoolean()) { return value.getAsBoolean(); } else if (value.isString()) { return value.getAsString(); } else if (value.isNumber()){ return value.getAsNumber(); } return null; } private static final Object toValue(JsonElement value) { if (value.isJsonNull()) { return null; } else if (value.isJsonArray()) { return toList((JsonArray) value); } else if (value.isJsonObject()) { return toMap((JsonObject) value); } else if (value.isJsonPrimitive()) { return toPrimitive((JsonPrimitive) value); } return null; } } 

FileLoader.java

 import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.Scanner; public class FileLoader { public static Reader openReader(String filename, boolean isResource) throws UnsupportedEncodingException, FileNotFoundException, MalformedURLException { return openReader(filename, isResource, "UTF-8"); } public static Reader openReader(String filename, boolean isResource, String charset) throws UnsupportedEncodingException, FileNotFoundException, MalformedURLException { return new InputStreamReader(openInputStream(filename, isResource), charset); } public static InputStream openInputStream(String filename, boolean isResource) throws FileNotFoundException, MalformedURLException { if (isResource) { return FileLoader.class.getClassLoader().getResourceAsStream(filename); } return new FileInputStream(load(filename, isResource)); } public static String read(String path, boolean isResource) throws IOException { return read(path, isResource, "UTF-8"); } public static String read(String path, boolean isResource, String charset) throws IOException { return read(pathToUrl(path, isResource), charset); } @SuppressWarnings("resource") protected static String read(URL url, String charset) throws IOException { return new Scanner(url.openStream(), charset).useDelimiter("\\A").next(); } protected static File load(String path, boolean isResource) throws MalformedURLException { return load(pathToUrl(path, isResource)); } protected static File load(URL url) { try { return new File(url.toURI()); } catch (URISyntaxException e) { return new File(url.getPath()); } } private static final URL pathToUrl(String path, boolean isResource) throws MalformedURLException { if (isResource) { return FileLoader.class.getClassLoader().getResource(path); } return new URL("file:/" + path); } } 

您也可以使用Jackson API:

  final String json = "....your json..."; final ObjectMapper mapper = new ObjectMapper(); final MapType type = mapper.getTypeFactory().constructMapType( Map.class, String.class, Object.class); final Map<String, Object> data = mapper.readValue(json, type); 

试试这个代码:

  Map<String, String> params = new HashMap<String, String>(); try { Iterator<?> keys = jsonObject.keys(); while (keys.hasNext()) { String key = (String) keys.next(); String value = jsonObject.getString(key); params.put(key, value); } } catch (Exception xx) { xx.toString(); }