conversión de cadena a objeto json android


107

Estoy trabajando en una aplicación para Android. En mi aplicación, tengo que convertir una cadena a Json Object, luego analizar los valores. Busqué una solución en stackoverflow y encontré un problema similar aquí enlace

La solucion es asi

       `{"phonetype":"N95","cat":"WP"}`
        JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");

Utilizo la misma forma en mi código. Mi cuerda es

{"ApiInfo":{"description":"userDetails","status":"success"},"userDetails":{"Name":"somename","userName":"value"},"pendingPushDetails":[]}

string mystring= mystring.replace("\"", "\\\"");

Y después de reemplazar obtuve el resultado como este

{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"Sarath Babu\",\"userName\":\"sarath.babu.sarath babu\",\"Token\":\"ZIhvXsZlKCNL6Xj9OPIOOz3FlGta9g\",\"userId\":\"118\"},\"pendingPushDetails\":[]}

cuando ejecuto JSONObject jsonObj = new JSONObject(mybizData);

Recibo la siguiente excepción json

org.json.JSONException: Expected literal value at character 1 of

Ayúdame a resolver mi problema.


Supongo que el personaje ofensivo es una barra invertida debido a tu sustitución. ¿Por qué exactamente estás haciendo eso? ¿De dónde viene la cadena JSON?
— tiguchi

Recibo la cadena de html ... no como json
— sarath

1
Simplemente elimine mystring = mystring.replace ("\" "," \\\ ""); y vea si funciona para usted entonces.
— tiguchi

Respuestas:


227

Quita las barras:

String json = {"phonetype":"N95","cat":"WP"};

try {

    JSONObject obj = new JSONObject(json);

    Log.d("My App", obj.toString());

} catch (Throwable t) {
    Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}

4
¿Qué pasa si la cadena es una matriz de objetos JSON? Como "[{}, {}, {}]"
— Francisco Corrales Morales

3
@FranciscoCorralesMorales puedes usar JSONArray obj = new JSONArray(json);. Luego puede usar un bucle for para iterar a través de la matriz.
— Phil

2
@FranciscoCorralesMorales solo usa un bloque try-catch . Si uno falla, asuma el otro.
— Phil

1
@ ripDaddy69 Parece que JSON no es válido. Espera emparejamientos clave-valor rodeados de llaves. Prueba algo como {"Fat cat":"meow"}.
— Phil

2
@Phil Eso no parece ser una asignación de cadena de Java válida. No entiendo qué estoy haciendo de manera diferente aunque JSONObject obj = new JSONObject ("Fat cat": "miau"); Lo descubrí, necesitaba usar \ delante de las comillas, y luego comillas reales alrededor de todo. Gracias.

31

es trabajo

    String json = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";

    try {

        JSONObject obj = new JSONObject(json);

        Log.d("My App", obj.toString());
        Log.d("phonetype value ", obj.getString("phonetype"));

    } catch (Throwable tx) {
        Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
    }

1
Si bien esto responde la pregunta, no explica por qué ni cómo funciona. Por favor agregue tal explicación.
— CerebralFart

Parece una solución de código simple, que requiere crear otro objeto que maneje la secuencia de escape.
— kelalaka

7

prueba esto:

String json = "{'phonetype':'N95','cat':'WP'}";

2
¿Qué pasa si la cadena es una matriz de objetos JSON? Como "[{}, {}, {}]"
— Francisco Corrales Morales

Esta es una buena idea. La comilla simple funciona y elimina la necesidad de caracteres de escape.
— David M Lee

1
Apostrophe podría funcionar, en JAVA, pero no es JSON estrictamente legal. Por lo tanto, es posible que deba hacer las cosas de manera diferente en otros idiomas o situaciones.
— Jesse Chisholm

4

Para obtener un JSONObject o JSONArray de una cadena, he creado esta clase:

public static class JSON {

     public Object obj = null;
     public boolean isJsonArray = false;

     JSON(Object obj, boolean isJsonArray){
         this.obj = obj;
         this.isJsonArray = isJsonArray;
     }
}

Aquí para obtener el JSON:

public static JSON fromStringToJSON(String jsonString){

    boolean isJsonArray = false;
    Object obj = null;

    try {
        JSONArray jsonArray = new JSONArray(jsonString);
        Log.d("JSON", jsonArray.toString());
        obj = jsonArray;
        isJsonArray = true;
    }
    catch (Throwable t) {
        Log.e("JSON", "Malformed JSON: \"" + jsonString + "\"");
    }

    if (object == null) {
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            Log.d("JSON", jsonObject.toString());
            obj = jsonObject;
            isJsonArray = false;
        } catch (Throwable t) {
            Log.e("JSON", "Malformed JSON: \"" + jsonString + "\"");
        }
    }

    return new JSON(obj, isJsonArray);
}

Ejemplo:

JSON json = fromStringToJSON("{\"message\":\"ciao\"}");
if (json.obj != null) {

    // If the String is a JSON array
    if (json.isJsonArray) {
        JSONArray jsonArray = (JSONArray) json.obj;
    }
    // If it's a JSON object
    else {
        JSONObject jsonObject = (JSONObject) json.obj;
    }
}

Puede probar el primer carácter de la cadena JSON para ver si lo es [o {para saber si es una matriz o un objeto. Entonces no estaría arriesgando ambas excepciones, solo la pertinente.
— Jesse Chisholm

3

solo prueba esto, finalmente esto funciona para mí:

//delete backslashes ( \ ) :
            data = data.replaceAll("[\\\\]{1}[\"]{1}","\"");
//delete first and last double quotation ( " ) :
            data = data.substring(data.indexOf("{"),data.lastIndexOf("}")+1);
            JSONObject json = new JSONObject(data);

3

Solo necesita las líneas de código de la siguiente manera:

 try {
        String myjsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
        JSONObject jsonObject = new JSONObject(myjsonString );
        //getting specific key values
        Log.d("phonetype = ", jsonObject.getString("phonetype"));
        Log.d("cat = ", jsonObject.getString("cat");
    }catch (Exception ex) {
         StringWriter stringWriter = new StringWriter();
         ex.printStackTrace(new PrintWriter(stringWriter));
         Log.e("exception ::: ", stringwriter.toString());
    }

0

Aquí está el código y puede decidir cuál
StringBuffer (sincronizado) o StringBuilder más rápido usar.

Benchmark muestra que StringBuilder es más rápido.

public class Main {
            int times = 777;
            long t;

            {
                StringBuffer sb = new StringBuffer();
                t = System.currentTimeMillis();
                for (int i = times; i --> 0 ;) {
                    sb.append("");
                    getJSONFromStringBuffer(String stringJSON);
                }
                System.out.println(System.currentTimeMillis() - t);
            }

            {
                StringBuilder sb = new StringBuilder();
                t = System.currentTimeMillis();
                for (int i = times; i --> 0 ;) {
                     getJSONFromStringBUilder(String stringJSON);
                    sb.append("");
                }
                System.out.println(System.currentTimeMillis() - t);
            }
            private String getJSONFromStringBUilder(String stringJSONArray) throws JSONException {
                return new StringBuffer(
                       new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
                           .append(" ")
                           .append(
                       new JSONArray(employeeID).getJSONObject(0).getString("cat"))
                      .toString();
            }
            private String getJSONFromStringBuffer(String stringJSONArray) throws JSONException {
                return new StringBuffer(
                       new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
                           .append(" ")
                           .append(
                       new JSONArray(employeeID).getJSONObject(0).getString("cat"))
                      .toString();
            }
        }

0

Puede estar debajo es mejor.

JSONObject jsonObject=null;
    try {
        jsonObject=new JSONObject();
        jsonObject.put("phonetype","N95");
        jsonObject.put("cat","wp");
        String jsonStr=jsonObject.toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.