crear Hashmap a partir de una cadena JSON

creando un hashmap a partir de una cadena json en java?

Tengo una cadena json como {"phonetype":"N95","cat":"WP"} y quiero convertirla en un Hashmap estándar.

¿Cómo puedo hacerlo?

Analice JSONObject y cree HashMap

 public static void jsonToMap(String t) throws JSONException { HashMap map = new HashMap(); JSONObject jObject = new JSONObject(t); Iterator keys = jObject.keys(); while( keys.hasNext() ){ String key = (String)keys.next(); String value = jObject.getString(key); map.put(key, value); } System.out.println("json : "+jObject); System.out.println("map : "+map); } 

Producto probado:

 json : {"phonetype":"N95","cat":"WP"} map : {cat=WP, phonetype=N95} 

Puede usar la biblioteca Gson de Google para convertir json a Hashmap. Pruebe el código siguiente

 String jsonString = "Your JSON string"; HashMap map = new Gson().fromJson(jsonString, new TypeToken>(){}.getType()); 
 public class JsonMapExample { public static void main(String[] args) { String json = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}"; Map map = new HashMap(); ObjectMapper mapper = new ObjectMapper(); try { //convert JSON string to Map map = mapper.readValue(json, new TypeReference>() {}); System.out.println(map); } catch (Exception e) { e.printStackTrace(); } } } 

Salida:

 {phonetype=N95, cat=WP} 

Puedes ver este enlace que es útil http://www.mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/

Podría usar la biblioteca Gson

 Type type = new TypeToken>() {}.getType(); new Gson().fromJson(jsonString, type); 
 HashMap hashMap = new HashMap(); String string = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}"; try { JSONObject json = new JSONObject(string); hashMap.put("phonetype", json.getString("phonetype")); hashMap.put("cat", json.getString("cat")); } catch (JSONException e) { // TODO Handle expection! } 

No hay bibliotecas JSON, solo String y HashMap.
Lo mantiene simple!
Espero que se adapte a todos.

// Ejemplo de JSON Transform to HashMap basado en String

  String tempJson = "{\"incomePhone\":\"213121122\",\"clientId\":\"1001\",\"clientAccountManager\":\"Gestor de Conta 1\",\"clientRetailBranch\":\"100\",\"phoneAccountManager\":\"7800100\"}"; System.out.println(tempJson); String[] parts = tempJson.split(","); HashMap jsonHash = new HashMap(); for(int i=0;i 

No hagas esto tú mismo, sugiero.
Utilice una biblioteca, por ejemplo, la biblioteca Gson de Google.

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

considerar esta cadena json

 { "12": [ { "dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/12/12_960x540_200k.mp4/manifest.mpd", "video_bitrate": "200k", "audio_bitrate": "32k", "video_width": 960, "video_height": 540, "file_size": 125465600 }, { "dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/12/12_960x540_80k.mp4/manifest.mpd", "video_bitrate": "80k", "audio_bitrate": "32k", "video_width": 960, "video_height": 540, "file_size": 50186240 }, { "dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/12/12_640x360_201k.mp4/manifest.mpd", "video_bitrate": "201k", "audio_bitrate": "32k", "video_width": 640, "video_height": 360, "file_size": 145934731 }, { "dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/12/12_640x360_199k.mp4/manifest.mpd", "video_bitrate": "199k", "audio_bitrate": "32k", "video_width": 640, "video_height": 360, "file_size": 145800030 }, { "dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/12/12_640x360_79k.mp4/manifest.mpd", "video_bitrate": "79k", "audio_bitrate": "32k", "video_width": 640, "video_height": 360, "file_size": 71709477 } ], "13": [ { "dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/13/13_960x540_200k.mp4/manifest.mpd", "video_bitrate": "200k", "audio_bitrate": "32k", "video_width": 960, "video_height": 540, "file_size": 172902400 }, { "dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/13/13_960x540_80k.mp4/manifest.mpd", "video_bitrate": "80k", "audio_bitrate": "32k", "video_width": 960, "video_height": 540, "file_size": 69160960 }, { "dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/13/13_640x360_201k.mp4/manifest.mpd", "video_bitrate": "201k", "audio_bitrate": "32k", "video_width": 640, "video_height": 360, "file_size": 199932081 }, { "dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/13/13_640x360_199k.mp4/manifest.mpd", "video_bitrate": "199k", "audio_bitrate": "32k", "video_width": 640, "video_height": 360, "file_size": 199630781 }, { "dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/13/13_640x360_79k.mp4/manifest.mpd", "video_bitrate": "79k", "audio_bitrate": "32k", "video_width": 640, "video_height": 360, "file_size": 98303415 } ], "14": [ { "dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/14/14_960x540_200k.mp4/manifest.mpd", "video_bitrate": "200k", "audio_bitrate": "32k", "video_width": 960, "video_height": 540, "file_size": 205747200 }, { "dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/14/14_960x540_80k.mp4/manifest.mpd", "video_bitrate": "80k", "audio_bitrate": "32k", "video_width": 960, "video_height": 540, "file_size": 82298880 }, { "dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/14/14_640x360_201k.mp4/manifest.mpd", "video_bitrate": "201k", "audio_bitrate": "32k", "video_width": 640, "video_height": 360, "file_size": 237769546 }, { "dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/14/14_640x360_199k.mp4/manifest.mpd", "video_bitrate": "199k", "audio_bitrate": "32k", "video_width": 640, "video_height": 360, "file_size": 237395552 }, { "dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/14/14_640x360_79k.mp4/manifest.mpd", "video_bitrate": "79k", "audio_bitrate": "32k", "video_width": 640, "video_height": 360, "file_size": 116885686 } ], "15": [ { "dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/15/15_960x540_200k.mp4/manifest.mpd", "video_bitrate": "200k", "audio_bitrate": "32k", "video_width": 960, "video_height": 540, "file_size": 176128000 }, { "dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/15/15_960x540_80k.mp4/manifest.mpd", "video_bitrate": "80k", "audio_bitrate": "32k", "video_width": 960, "video_height": 540, "file_size": 70451200 }, { "dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/15/15_640x360_201k.mp4/manifest.mpd", "video_bitrate": "201k", "audio_bitrate": "32k", "video_width": 640, "video_height": 360, "file_size": 204263286 }, { "dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/15/15_640x360_199k.mp4/manifest.mpd", "video_bitrate": "199k", "audio_bitrate": "32k", "video_width": 640, "video_height": 360, "file_size": 204144447 }, { "dash_url": "http://mediaserver.superprofs.com:1935/vods3/_definst_/mp4:amazons3/superprofs-media/private/lectures/15/15_640x360_79k.mp4/manifest.mpd", "video_bitrate": "79k", "audio_bitrate": "32k", "video_width": 640, "video_height": 360, "file_size": 100454382 } ] } 

usando el analizador de jackson

  private static ObjectMapper underScoreToCamelCaseMapper; static { final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); underScoreToCamelCaseMapper = new ObjectMapper(); underScoreToCamelCaseMapper.setDateFormat(df); underScoreToCamelCaseMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); underScoreToCamelCaseMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); underScoreToCamelCaseMapper.setPropertyNamingStrategy( PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); } public static  T parseUnderScoredResponse(String json, Class classOfT) { try { if (json == null) { return null; } return underScoreToCamelCaseMapper.readValue(json, classOfT); } catch (JsonParseException e) { } catch (JsonMappingException e) { } catch (IOException e) { } return null; } 

use el siguiente código para analizar

  HashMap> integerArrayListHashMap = JsonHandler.parseUnderScoredResponse(test, MyHashMap.class); 

donde MyHashMap es

  private static class MyHashMap extends HashMap>{ } 
 public Map parseJSON(JSONObject json, Map dataFields) throws JSONException { Iterator keys = json.keys(); while (keys.hasNext()) { String key = keys.next(); String val = null; try { JSONObject value = json.getJSONObject(key); parseJSON(value, dataFields); } catch (Exception e) { if (json.isNull(key)) { val = ""; } else { try { val = json.getString(key); } catch (Exception ex) { System.out.println(ex.getMessage()); } } } if (val != null) { dataFields.put(key, val); } } return dataFields; } 

Esta es una operación simple sin necesidad de usar ninguna biblioteca externa.

Puede usar esta clase en su lugar 🙂 (maneja listas uniformes, listas anidadas y json)

 public class Utility { public static Map jsonToMap(Object json) throws JSONException { if(json instanceof JSONObject) return _jsonToMap_((JSONObject)json) ; else if (json instanceof String) { JSONObject jsonObject = new JSONObject((String)json) ; return _jsonToMap_(jsonObject) ; } return null ; } private static Map _jsonToMap_(JSONObject json) throws JSONException { Map retMap = new HashMap(); if(json != JSONObject.NULL) { retMap = toMap(json); } return retMap; } private static Map toMap(JSONObject object) throws JSONException { Map map = new HashMap(); Iterator 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 toList(JSONArray array) throws JSONException { List list = new ArrayList(); 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; } } 

Para convertir su cadena JSON en hashmap, use esto:

 HashMap hashMap = new HashMap<>(Utility.jsonToMap(response)) ; 

La mejor forma de analizar Json a HashMap

 public static HashMap jsonToMap(JSONObject json) throws JSONException { HashMap map = new HashMap<>(); try { Iterator iterator = json.keys(); while (iterator.hasNext()) { String key = iterator.next(); String value = json.getString(key); map.put(key, value); } return map; } catch (JSONException e) { e.printStackTrace(); } return null; } 

Podrías usar a Jackson para hacer esto. Todavía tengo que encontrar una solución simple de Gson.

Donde data_map.json es un archivo de recursos JSON (objeto)
y data_list.json es un archivo de recursos JSON (matriz).

 import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.List; import java.util.Map; import java.util.Scanner; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * Based on: * * http://www.mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/ */ public class JsonLoader { private static final ObjectMapper OBJ_MAPPER; private static final TypeReference> OBJ_MAP; private static final TypeReference>> OBJ_LIST; static { OBJ_MAPPER = new ObjectMapper(); OBJ_MAP = new TypeReference>(){}; OBJ_LIST = new TypeReference>>(){}; } public static void main(String[] args) { try { System.out.println(jsonToString(parseJsonString(read("data_map.json", true)))); System.out.println(jsonToString(parseJsonString(read("data_array.json", true)))); } catch (IOException e) { e.printStackTrace(); } } private static final Object parseJsonString(String jsonString) { try { if (jsonString.startsWith("{")) { return readJsonObject(jsonString); } else if (jsonString.startsWith("[")) { return readJsonArray(jsonString); } } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static String jsonToString(Object json) throws JsonProcessingException { return OBJ_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(json); } private static final Map readJsonObject(String jsonObjectString) throws JsonParseException, JsonMappingException, IOException { return OBJ_MAPPER.readValue(jsonObjectString, OBJ_MAP); } private static final List> readJsonArray(String jsonArrayString) throws JsonParseException, JsonMappingException, IOException { return OBJ_MAPPER.readValue(jsonArrayString, OBJ_LIST); } public static final Map loadJsonObject(String path, boolean isResource) throws JsonParseException, JsonMappingException, MalformedURLException, IOException { return OBJ_MAPPER.readValue(load(path, isResource), OBJ_MAP); } public static final List> loadJsonArray(String path, boolean isResource) throws JsonParseException, JsonMappingException, MalformedURLException, IOException { return OBJ_MAPPER.readValue(load(path, isResource), OBJ_LIST); } private static final URL pathToUrl(String path, boolean isResource) throws MalformedURLException { if (isResource) { return JsonLoader.class.getClassLoader().getResource(path); } return new URL("file:/" + path); } 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()); } } public static String read(String path, boolean isResource) throws IOException { return read(path, "UTF-8", isResource); } public static String read(String path, String charset, boolean isResource) throws IOException { return read(pathToUrl(path, isResource), charset); } @SuppressWarnings("resource") public static String read(URL url, String charset) throws IOException { return new Scanner(url.openStream(), charset).useDelimiter("\\A").next(); } } 

Extra

Aquí está el código completo para el ejemplo de Dheeraj Sachan .

 import java.io.File; import java.io.IOException; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.Scanner; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; public class JsonHandler { private static ObjectMapper propertyMapper; static { final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); propertyMapper = new ObjectMapper(); propertyMapper.setDateFormat(df); propertyMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); propertyMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); propertyMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); } private static class MyHashMap extends HashMap>{ private static final long serialVersionUID = 7023107716981734468L; } private static class Video implements Serializable { private static final long serialVersionUID = -446275421030765463L; private String dashUrl; private String videoBitrate; private String audioBitrate; private int videoWidth; private int videoHeight; private long fileSize; @Override public String toString() { return "Video [url=" + dashUrl + ", video=" + videoBitrate + ", audio=" + audioBitrate + ", width=" + videoWidth + ", height=" + videoHeight + ", size=" + fileSize + "]"; } } public static void main(String[] args) { try { HashMap