Convertir une chaîne JSON en HashMap

J’utilise Java et j’ai un Ssortingng qui est JSON:

{ "name" : "abc" , "email id " : ["[email protected]","[email protected]","[email protected]"] } 

Puis ma carte en Java:

 Map retMap = new HashMap(); 

Je souhaite stocker toutes les données du JSONObject dans ce HashMap.

Quelqu’un peut-il fournir un code pour cela? Je veux utiliser la bibliothèque org.json .

J’ai écrit ce code il y a quelques jours par récursivité.

 public static Map jsonToMap(JSONObject json) throws JSONException { Map retMap = new HashMap(); if(json != JSONObject.NULL) { retMap = toMap(json); } return retMap; } public static Map toMap(JSONObject object) throws JSONException { Map map = new HashMap(); Iterator keysItr = object.keys(); while(keysItr.hasNext()) { Ssortingng 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; } 

En utilisant GSon , vous pouvez effectuer les opérations suivantes:

 Map retMap = new Gson().fromJson( jsonSsortingng, new TypeToken>() {}.getType() ); 

J’espère que cela fonctionnera, essayez ceci:

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

str, votre chaîne JSON

Aussi simple que cela, si vous voulez emailid,

 Ssortingng emailIds = response.get("email id").toSsortingng(); 

Voici le code de Vikas porté sur 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 jsonToMap(JsonObject json) { Map retMap = new HashMap(); if(json != JsonObject.NULL) { retMap = toMap(json); } return retMap; } public static Map toMap(JsonObject object) throws JsonException { Map map = new HashMap(); Iterator keysItr = object.keySet().iterator(); while(keysItr.hasNext()) { Ssortingng 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) { List list = new ArrayList(); 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; } } 

Conversion d’une chaîne JSON en carte

 public static Map jsonSsortingng2Map( Ssortingng jsonSsortingng ) throws JSONException{ Map keys = new HashMap(); org.json.JSONObject jsonObject = new org.json.JSONObject( jsonSsortingng ); // HashMap Iterator keyset = jsonObject.keys(); // HM while (keyset.hasNext()) { Ssortingng key = (Ssortingng) 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, jsonSsortingng2Map( value.toSsortingng() )); }else if ( value instanceof org.json.JSONArray) { org.json.JSONArray jsonArray = jsonObject.getJSONArray(key); //JSONArray jsonArray = new JSONArray(value.toSsortingng()); keys.put( key, jsonArray2List( jsonArray )); } else { keyNode( value); keys.put( key, value ); } } return keys; } 

Conversion d’un tableau JSON en liste

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

Afficher JSON de n’importe quel format

 public static void displayJSONMAP( Map allKeys ) throws Exception{ Set keyset = allKeys.keySet(); // HM$keyset if (! keyset.isEmpty()) { Iterator keys = keyset.iterator(); // HM$keysIterator while (keys.hasNext()) { Ssortingng key = keys.next(); Object value = allKeys.get( key ); if ( value instanceof Map ) { System.out.println("\n Object Key : "+key); displayJSONMAP(jsonSsortingng2Map(value.toSsortingng())); }else if ( value instanceof List ) { System.out.println("\n Array Key : "+key); JSONArray jsonArray = new JSONArray(value.toSsortingng()); 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 jsonToMap(JSONObject json) { Map retMap = new HashMap(); if(json != null) { retMap = toMap(json); } return retMap; } public static Map toMap(JSONObject object) { Map map = new HashMap(); Iterator keysItr = object.keySet().iterator(); while(keysItr.hasNext()) { Ssortingng 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) { List list = new ArrayList(); 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; } } 

Vous pouvez également utiliser l’API Jackson pour cela:

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

Vous pouvez convertir n’importe quel JSON en map en utilisant la bibliothèque Jackson comme ci-dessous:

 Ssortingng json = "{\r\n\"name\" : \"abc\" ,\r\n\"email id \" : [\"[email protected]\",\"[email protected]\",\"[email protected]\"]\r\n}"; ObjectMapper mapper = new ObjectMapper(); Map map = new HashMap(); // convert JSON ssortingng to Map map = mapper.readValue(json, new TypeReference>() {}); System.out.println(map); 

Dépendances Maven pour Jackson :

  com.fasterxml.jackson.core jackson-core 2.5.3 comstack   com.fasterxml.jackson.core jackson-databind 2.5.3 comstack  

J’espère que cela aidera. Heureux codage 🙂

essayez ce code:

  Map params = new HashMap(); try { Iterator keys = jsonObject.keys(); while (keys.hasNext()) { Ssortingng key = (Ssortingng) keys.next(); Ssortingng value = jsonObject.getSsortingng(key); params.put(key, value); } } catch (Exception xx) { xx.toSsortingng(); } 

Imaginez que vous ayez une liste de courrier électronique comme ci-dessous. pas contraint à un langage de programmation,

 emailsList = ["[email protected]","[email protected]","[email protected]"] 

Maintenant, voici le code JAVA – pour convertir json en carte

 JSONObject jsonObj = new JSONObject().put("name","abc").put("email id",emailsList); Map s = jsonObj.getMap(); 

Vous pouvez utiliser la bibliothèque google gson pour convertir un object json.

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

D’autres bibliothèques comme Jackson sont également disponibles.

Cela ne le convertira pas en carte. Mais vous pouvez faire toutes les choses que vous voulez.

Bref et utile:

 /** * @param jsonThing can be a JsonObject, a JsonArray, * a Boolean, a Number, * a null or a JSONObject.NULL. * @return Appropriate Java Object, that may be a Map, a List, * a Boolean, a Number or a null. */ public static Object jsonThingToAppropriateJavaObject(Object jsonThing) throws JSONException { if (jsonThing instanceof JSONArray) { final ArrayList list = new ArrayList<>(); final JSONArray jsonArray = (JSONArray) jsonThing; final int l = jsonArray.length(); for (int i = 0; i < l; ++i) list.add(jsonThingToAppropriateJavaObject(jsonArray.get(i))); return list; } if (jsonThing instanceof JSONObject) { final HashMap map = new HashMap<>(); final Iterator keysItr = ((JSONObject) jsonThing).keys(); while (keysItr.hasNext()) { final Ssortingng key = keysItr.next(); map.put(key, jsonThingToAppropriateJavaObject(((JSONObject) jsonThing).get(key))); } return map; } if (JSONObject.NULL.equals(jsonThing)) return null; return jsonThing; } 

Merci @Vikas Gupta .

L’parsingur suivant lit un fichier, l’parsing dans un JsonElement générique, en utilisant la méthode JsonParser.parse de Google, puis convertit tous les éléments du JSON généré en une List Java native List ou Map .

Note : Le code ci-dessous est basé sur la réponse de 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(Ssortingng[] 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).toSsortingng()); } public static Map loadJsonObject(Ssortingng filename, boolean isResource) throws UnsupportedEncodingException, FileNotFoundException, JsonIOException, JsonSyntaxException, MalformedURLException { return jsonToMap(loadJson(filename, isResource).getAsJsonObject()); } public static List loadJsonArray(Ssortingng filename, boolean isResource) throws UnsupportedEncodingException, FileNotFoundException, JsonIOException, JsonSyntaxException, MalformedURLException { return jsonToList(loadJson(filename, isResource).getAsJsonArray()); } private static JsonElement loadJson(Ssortingng 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 jsonToMap(JsonObject jsonObject) { if (jsonObject.isJsonNull()) { return new HashMap(); } return toMap(jsonObject); } public static List jsonToList(JsonArray jsonArray) { if (jsonArray.isJsonNull()) { return new ArrayList(); } return toList(jsonArray); } private static final Map toMap(JsonObject object) { Map map = new HashMap(); for (Entry pair : object.entrySet()) { map.put(pair.getKey(), toValue(pair.getValue())); } return map; } private static final List toList(JsonArray array) { List list = new ArrayList(); 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.isSsortingng()) { return value.getAsSsortingng(); } 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(Ssortingng filename, boolean isResource) throws UnsupportedEncodingException, FileNotFoundException, MalformedURLException { return openReader(filename, isResource, "UTF-8"); } public static Reader openReader(Ssortingng filename, boolean isResource, Ssortingng charset) throws UnsupportedEncodingException, FileNotFoundException, MalformedURLException { return new InputStreamReader(openInputStream(filename, isResource), charset); } public static InputStream openInputStream(Ssortingng filename, boolean isResource) throws FileNotFoundException, MalformedURLException { if (isResource) { return FileLoader.class.getClassLoader().getResourceAsStream(filename); } return new FileInputStream(load(filename, isResource)); } public static Ssortingng read(Ssortingng path, boolean isResource) throws IOException { return read(path, isResource, "UTF-8"); } public static Ssortingng read(Ssortingng path, boolean isResource, Ssortingng charset) throws IOException { return read(pathToUrl(path, isResource), charset); } @SuppressWarnings("resource") protected static Ssortingng read(URL url, Ssortingng charset) throws IOException { return new Scanner(url.openStream(), charset).useDelimiter("\\A").next(); } protected static File load(Ssortingng 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(Ssortingng path, boolean isResource) throws MalformedURLException { if (isResource) { return FileLoader.class.getClassLoader().getResource(path); } return new URL("file:/" + path); } } 

En utilisant json-simple, vous pouvez convertir les données JSON en carte et mapper en JSON.

 try { JSONObject obj11 = new JSONObject(); obj11.put(1, "Kishan"); obj11.put(2, "Radhesh"); obj11.put(3, "Sonal"); obj11.put(4, "Madhu"); Map map = new HashMap(); obj11.toJSONSsortingng(); map = obj11; System.out.println(map.get(1)); JSONObject obj12 = new JSONObject(); obj12 = (JSONObject) map; System.out.println(obj12.get(1)); } catch(Exception e) { System.err.println("EROR : 01 :"+e); } 

Si vous n’aimez pas la récursivité – en utilisant une stack et javax.json pour convertir une chaîne Json en une liste de cartes:

 import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Stack; import javax.json.Json; import javax.json.stream.JsonParser; public class TestCreateObjFromJson { public static List> extract(InputStream is) { List extracted = new ArrayList<>(); JsonParser parser = Json.createParser(is); String nextKey = ""; Object nextval = ""; Stack s = new Stack<>(); while(parser.hasNext()) { JsonParser.Event event = parser.next(); switch(event) { case START_ARRAY : List nextList = new ArrayList<>(); if(!s.empty()) { // If this is not the root object, add it to tbe parent object setValue(s,nextKey,nextList); } s.push(nextList); break; case START_OBJECT : Map nextMap = new HashMap<>(); if(!s.empty()) { // If this is not the root object, add it to tbe parent object setValue(s,nextKey,nextMap); } s.push(nextMap); break; case KEY_NAME : nextKey = parser.getString(); break; case VALUE_STRING : setValue(s,nextKey,parser.getString()); break; case VALUE_NUMBER : setValue(s,nextKey,parser.getLong()); break; case VALUE_TRUE : setValue(s,nextKey,true); break; case VALUE_FALSE : setValue(s,nextKey,false); break; case VALUE_NULL : setValue(s,nextKey,""); break; case END_OBJECT : case END_ARRAY : if(s.size() > 1) { // If this is not a root object, move up s.pop(); } else { // If this is a root object, add ir ro rhw final extracted.add(s.pop()); } default : break; } } return extracted; } private static void setValue(Stack s, Ssortingng nextKey, Object v) { if(Map.class.isAssignableFrom(s.peek().getClass()) ) ((Map)s.peek()).put(nextKey, v); else ((List)s.peek()).add(v); } }