Convertir JSON en Mapa


¿Cuál es la mejor manera de convertir un código JSON de esta manera:

{ 
    "data" : 
    { 
        "field1" : "value1", 
        "field2" : "value2"
    }
}

En un mapa Java en el que una de las claves son (field1, field2) y los valores para esos campos son (value1, value2).

¿Alguna idea? ¿Debería usar Json-lib para eso? ¿O mejor si escribo mi propio analizador?

Author: Donald Duck, 2009-01-14

14 answers

Espero que estuvieras bromeando sobre escribir tu propio analizador. :-)

Para un mapeo tan simple, la mayoría de las herramientas de http://json.org (sección java) funcionaría. Para uno de ellos (Jackson, http://wiki.fasterxml.com/JacksonInFiveMinutes ), usted haría:

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

(donde JSON_SOURCE es un archivo, flujo de entrada, lector o cadena de contenido json)

 271
Author: StaxMan,
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
2012-04-08 00:54:51

Me gusta google gson biblioteca.
Cuando no conoces la estructura de json. Puede usar

JsonElement root = new JsonParser().parse(jsonString);

Y luego puedes trabajar con json. por ejemplo, cómo obtener "value1"de su gson:

String value1 = root.getAsJsonObject().get("data").getAsJsonObject().get("field1").getAsString();
 29
Author: bugs_,
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
2011-12-01 10:15:31

Usando la biblioteca GSON:

import com.google.gson.Gson
import com.google.common.reflect.TypeToken
import java.lang.reclect.Type

Utilice el siguiente código:

Type mapType = new TypeToken<Map<String, Map>>(){}.getType();  
Map<String, String[]> son = new Gson().fromJson(easyString, mapType);
 27
Author: David L,
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-02-11 18:58:25

Use JSON lib, por ejemplo 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));

}
 14
Author: j.d.,
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-01-14 16:58:25

Mi post podría ser útil para otros, así que imagina que tienes un mapa con un objeto específico en valores, algo así:

{  
   "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
      }
   }
}

Para analizar este archivo JSON con la biblioteca GSON, es fácil : si su proyecto está mavenized

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.3.1</version>
</dependency>

Luego usa este fragmento :

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

El POJO correspondiente debe ser algo así:

public class ShoppingList {

    int id;

    String label;

    boolean current;

    int nb_reference;

    //Setters & Getters !!!!!
}

Espero que ayude !

 11
Author: Jad B.,
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-08-18 07:46:35

De esta manera funciona como un Mapa...

JSONObject fieldsJson = new JSONObject(json);
String value = fieldsJson.getString(key);

<dependency>
    <groupId>org.codehaus.jettison</groupId>
    <artifactId>jettison</artifactId>
    <version>1.1</version>
</dependency>
 4
Author: Fabio Araujo,
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-01-23 11:00:37
java.lang.reflect.Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
Gson gson = new Gson();
Map<String, Object> categoryicons = gson.fromJson(json, mapType );
 3
Author: newMaziar,
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-08-13 14:10:09

Lo hago de esta manera. Es 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);
    }
}
 3
Author: Pavankumar B,
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-04-05 05:45:32

La biblioteca JsonTools es muy completa. Se puede encontrar en Github.

 2
Author: Bruno Ranschaert,
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-10-06 15:22:09

Una alternativa más, es json-simple que se puede encontrar en Maven Central:

(JSONObject)JSONValue.parse(someString); //JSONObject is actually a Map.

El artefacto es de 24kbytes, no tiene otras dependencias de tiempo de ejecución.

 1
Author: pcjuzer,
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-03-18 10:58:56

Con Gson 2.7 de Google (probablemente versiones anteriores también, pero he probado 2.7) es tan simple como:

Map map = gson.fromJson(json, Map.class);

Que devuelve un mapa de tipo class com.google.gson.internal.LinkedTreeMap y funciona recursivamente en objetos anidados.

 1
Author: isapir,
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-09-12 05:51:15
import net.sf.json.JSONObject

JSONObject.fromObject(yourJsonString).toMap
 0
Author: Li Rao,
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-10-26 07:00:16

La biblioteca Underscore-java puede convertir una cadena json en un mapa hash. Soy el mantenedor del proyecto.

Ejemplo de código:

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}
    }
}
 0
Author: Valentyn Kolesnikov,
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-28 00:21:42

JSON para Mapear siempre va a ser un tipo de datos string/object. tengo GSON lib de Google.

Funciona muy bien y JDK 1.5 es el requisito mínimo.

 -1
Author: ,
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
2009-06-12 16:03:59