Cómo convertir jsonString a JSONObject en Java


Tengo una variable de cadena llamada jsonString:

{"phonetype":"N95","cat":"WP"}

Ahora quiero convertirlo en objeto JSON. Busqué más en Google, pero no obtuve ninguna respuesta esperada...

Author: Raj Rajeshwar Singh Rathore, 2011-03-09

15 answers

Usando org.json biblioteca:

JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
 523
Author: dogbane,
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-16 10:42:46

Para cualquiera que todavía esté buscando una respuesta:

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);
 119
Author: Mappan,
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-09-30 01:01:02

Puede usar google-gson. Detalles:

Ejemplos de objetos

class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  private transient int value3 = 3;
  BagOfPrimitives() {
    // no-args constructor
  }
}

(Serialización)

BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj); 
==> json is {"value1":1,"value2":"abc"}

Tenga en cuenta que no puede serializar objetos con referencias circulares ya que eso resultará en recursión infinita.

(Deserialización)

BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);  
==> obj2 is just like obj

Otro ejemplo de Gson:

Gson es fácil de aprender e implementar, lo que necesita saber es los siguientes dos métodos:

- > toJSON () - convertir objeto java a Formato JSON

- > fromJson () - convierte JSON en objeto java

import com.google.gson.Gson;

public class TestObjectToJson {
  private int data1 = 100;
  private String data2 = "hello";

  public static void main(String[] args) {
      TestObjectToJson obj = new TestObjectToJson();
      Gson gson = new Gson();

      //convert java object to JSON format
      String json = gson.toJson(obj);

      System.out.println(json);
  }

}

Salida

{"data1":100,"data2":"hello"}

Recursos:

Página de inicio del Proyecto Gson de Google

Guía del usuario de Gson

Ejemplo

 39
Author: kamaci,
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-03-09 13:16:14

Hay varios serializadores y deserializadores Java JSON vinculados desde la página de inicio de JSON.

Al momento de escribir esto, hay estos 20:

...pero, por supuesto, la lista puede cambiar.

 28
Author: T.J. Crowder,
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-05-20 13:34:29

Solución Java 7

import javax.json.*;

...

String TEXT;
JsonObject body = Json.createReader(new StringReader(TEXT)).readObject()

;

 22
Author: RSG,
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-03-23 17:48:05

Me gusta usar google-gson para esto, y es precisamente porque no necesito trabajar con JSONObject directamente.

En ese caso tendría una clase que corresponderá a las propiedades de su objeto JSON

class Phone {
 public String phonetype;
 public String cat;
}


...
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
Gson gson = new Gson();
Phone fooFromJson = gson.fromJson(jsonString, Phone.class);
...

Sin embargo, creo que su pregunta es más como, ¿Cómo endup con un objeto JSONObject real de una cadena JSON.

Estaba mirando la api de google-json y no pude encontrar nada tan sencillo como org.api de json, que es probablemente lo que quieres ser usando si usted está tan fuertemente en necesidad de utilizar un barebones JSONObject.

Http://www.json.org/javadoc/org/json/JSONObject.html

Con org.json.JSONObject (otra API completamente diferente) Si quieres hacer algo como...

JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
System.out.println(jsonObject.getString("phonetype"));

Creo que la belleza de google-gson es que no es necesario tratar con JSONObject. Solo tienes que agarrar json, pasar la clase a la que quieres deserializar, y los atributos de la clase se compararán con el JSON, pero de nuevo, todos tiene sus propios requisitos, tal vez no puede darse el lujo de tener clases pre-mapeadas en el lado deserializing porque las cosas pueden ser demasiado dinámicas en el lado de generación de JSON. En ese caso, solo use json.org.

 9
Author: Gubatron,
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-03-09 13:23:36

Debe importar org.json

JSONObject jsonObj = null;
        try {
            jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
        } catch (JSONException e) {
            e.printStackTrace();
        }
 8
Author: Cabezas,
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-09-11 10:21:30

Para convertir String en JSONObject solo necesita pasar la instancia String al Constructor de JSONObject.

Eg:

JSONObject jsonObj = new JSONObject("your string");
 8
Author: Charu,
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-12-20 04:31:23

Si está utilizando http://json-lib.sourceforge.net (neto.ficción.json.JSONObject)

Es bastante fácil:

String myJsonString;
JSONObject json = JSONObject.fromObject(myJsonString);

O

JSONObject json = JSONSerializer.toJSON(myJsonString);

Obtener los valores entonces con json.getString (param), json.getInt (param) y así sucesivamente.

 3
Author: Thero,
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
2013-04-03 11:07:36

Utilice JsonNode de fasterxml para el análisis genérico de Json. Crea internamente un Mapa de valor clave para todas las entradas.

Ejemplo:

private void test(@RequestBody JsonNode node)

Cadena de entrada:

{"a":"b","c":"d"}
 3
Author: Vishnu,
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-08 14:05:59

Para convertir una cadena a json y el sting es como json. {"phonetype": "N95", "cat": "WP"}

String Data=response.getEntity().getText().toString(); // reading the string value 
JSONObject json = (JSONObject) new JSONParser().parse(Data);
String x=(String) json.get("phonetype");
System.out.println("Check Data"+x);
String y=(String) json.get("cat");
System.out.println("Check Data"+y);
 2
Author: Aravind Cheekkallur,
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
2013-10-10 05:49:54

Para establecer un único objeto json en la lista ie

"locations":{

}

En a List<Location>

Use

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

Jackson.mapper-asl-1.9.7.jar

 0
Author: user3012570,
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-01-06 13:22:10

TENGA en cuenta que GSON con deserialización de una interfaz resultará en una excepción como la siguiente.

"java.lang.RuntimeException: Unable to invoke no-args constructor for interface XXX. Register an InstanceCreator with Gson for this type may fix this problem."

While deserialize; GSON don't know which object has to be intantiated for that interface.

Esto se resuelve de alguna manera aquí.

Sin embargo FlexJSON tiene esta solución inherentemente. mientras que serializar el tiempo que está agregando nombre de clase como parte de json como a continuación.

{
    "HTTPStatus": "OK",
    "class": "com.XXX.YYY.HTTPViewResponse",
    "code": null,
    "outputContext": {
        "class": "com.XXX.YYY.ZZZ.OutputSuccessContext",
        "eligible": true
    }
}

Así que JSON será cumber algunos; pero no es necesario escribir InstanceCreator que se requiere en GSON.

 0
Author: Kanagavelu Sugumar,
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 11:47:29

No es necesario utilizar ninguna biblioteca externa.

Puedes usar esta clase en su lugar:) (maneja listas pares , listas anidadas y json)

public class Utility {

    public static Map<String, Object> 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<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
        Map<String, Object> retMap = new HashMap<String, Object>();

        if(json != JSONObject.NULL) {
            retMap = toMap(json);
        }
        return retMap;
    }


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

Para convertir tu cadena JSON a hashmap usa esto:

HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(
 0
Author: Natesh bhat,
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-01 07:59:31

Mejor ir con una forma más simple mediante el uso de org.json lib. Simplemente haga un enfoque muy simple como se muestra a continuación:

JSONObject obj = new JSONObject();
obj.put("phonetype", "N95");
obj.put("cat", "WP");

Ahora obj es la forma convertida JSONObject de su Cadena respectiva. Esto es en caso de que tenga pares nombre-valor.

Para una cadena, se puede pasar directamente al constructor de JSONObject. Si va a ser un json String válido, entonces bien de lo contrario va a lanzar una excepción.

 -1
Author: TheLittleNaruto,
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-11-11 12:58:55