Convertir una cadena JSON a un HashMap


Estoy usando Java, y tengo una cadena que es JSON:

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

Entonces mi mapa en Java:

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

Quiero almacenar todos los datos del JSONObject en ese HashMap.

¿Puede alguien proporcionar código para esto? Quiero usar la biblioteca org.json.

Author: Dayan, 2014-02-12

15 answers

Escribí este código hace unos días por recursión.

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;
}
 184
Author: Vikas Gupta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-05 04:08:23

Usando GSon , puedes hacer lo siguiente:

Map<String, Object> retMap = new Gson().fromJson(
    jsonString, new TypeToken<HashMap<String, Object>>() {}.getType()
);
 89
Author: Toon Borgers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-26 10:08:38

Espero que esto funcione, prueba esto:

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

Str, tu cadena JSON

Tan simple como esto, si quieres emailid,

String emailIds = response.get("email id").toString();
 14
Author: MukilanKarthikeyan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-08 15:41:40

Aquí está el código de Vikas portado a 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;
    }
}
 5
Author: Kolban,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-28 18:29:52

Convertir una cadena JSON a Map

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

Convertir matriz JSON a List

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

Mostrar JSON de Cualquier formato

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 a HashMap.

 4
Author: Yash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:51
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;
    }
}
 4
Author: user3617834,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-19 22:01:51

También puedes usar la API de Jackson para esto:

    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);
 2
Author: Swapnil Jaju,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-26 10:05:25

Puedes convertir cualquier JSON a map usando la biblioteca Jackson de la siguiente manera:

String json = "{\r\n\"name\" : \"abc\" ,\r\n\"email id \" : [\"[email protected]\",\"[email protected]\",\"[email protected]\"]\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);

Dependencias Maven para Jackson :

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

Espero que esto ayude. Feliz codificación :)

 2
Author: Ankur Mahajan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-06 15:57:50

Prueba este código:

 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();
                }
 2
Author: Osama Ibrahim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-11 10:25:08

Imagine que tiene una lista de correo electrónico como a continuación. no limitado a ningún lenguaje de programación,

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

Ahora sigue el código JAVA-para convertir json a map

JSONObject jsonObj = new JSONObject().put("name","abc").put("email id",emailsList);
Map<String, Object> s = jsonObj.getMap();
 2
Author: Abhijith Anil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-22 11:30:49

Puede usar la biblioteca gson de Google para convertir objetos json.

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

Otras bibliotecas como Jackson también están disponibles.

Esto no lo convertirá en un mapa. Pero puedes hacer todas las cosas que quieras.

 1
Author: Konza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-12 07:05:20

Breve y útil:

/**
 * @param jsonThing can be a <code>JsonObject</code>, a <code>JsonArray</code>,
 *                     a <code>Boolean</code>, a <code>Number</code>,
 *                     a <code>null</code> or a <code>JSONObject.NULL</code>.
 * @return <i>Appropriate Java Object</i>, that may be a <code>Map</code>, a <code>List</code>,
 * a <code>Boolean</code>, a <code>Number</code> or a <code>null</code>.
 */
public static Object jsonThingToAppropriateJavaObject(Object jsonThing) throws JSONException {
    if (jsonThing instanceof JSONArray) {
        final ArrayList<Object> 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<String, Object> map = new HashMap<>();

        final Iterator<String> keysItr = ((JSONObject) jsonThing).keys();
        while (keysItr.hasNext()) {
            final String key = keysItr.next();
            map.put(key, jsonThingToAppropriateJavaObject(((JSONObject) jsonThing).get(key)));
        }
        return map;
    }

    if (JSONObject.NULL.equals(jsonThing)) return null;

    return jsonThing;
}

Gracias @Vikas Gupta .

 1
Author: Mir-Ismaili,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-06 22:31:23

El siguiente analizador lee un archivo, lo analiza en un JsonElement genérico, utilizando el método JsonParser.parse de Google, y luego convierte todos los elementos en el JSON generado en un Java nativo List<object> o Map<String, Object>.

Nota: El siguiente código se basa Vikas Gupta's respuesta.

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

Cargador de archivos.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);
    }
}
 0
Author: Mr. Polywhirl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:40

Usando json-simple puede convertir datos JSON a Map y Mapear a 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.toJSONString();

    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);
}
 0
Author: mak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-02 12:54:07

Si odias la recursión, usa una pila y javax.json para convertir una cadena Json en una Lista de Mapas:

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<Map<String,Object>> 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<String,Object> 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, String nextKey, Object v) {
        if(Map.class.isAssignableFrom(s.peek().getClass()) ) ((Map)s.peek()).put(nextKey, v);
        else ((List)s.peek()).add(v);
    }
}
 0
Author: hareluya86,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-05 15:07:48