conversione da stringa a oggetto json android


107

Sto lavorando a un'applicazione Android. Nella mia app devo convertire una stringa in Json Object, quindi analizzare i valori. Ho cercato una soluzione in stackoverflow e ho trovato un problema simile qui link

La soluzione è così

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

Uso allo stesso modo nel mio codice. La mia stringa è

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

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

E dopo la sostituzione ho ottenuto il risultato come questo

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

quando eseguo JSONObject jsonObj = new JSONObject(mybizData);

Ricevo l'eccezione JSON di seguito

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

Per favore aiutami a risolvere il mio problema.


Immagino che il personaggio offensivo sia una barra rovesciata a causa della tua sostituzione. Perché lo fai esattamente? Da dove viene la stringa JSON?
— tiguchi

Ricevo la stringa da html .. non come json
— sarath

1
Basta rimuovere mystring = mystring.replace ("\" "," \\\ ""); e vedi se funziona per te allora.
— tiguchi

Risposte:


227

Rimuovi le barre:

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
cosa succede se la stringa è un array di oggetti JSON? Come "[{}, {}, {}]"
— Francisco Corrales Morales

3
@FranciscoCorralesMorales puoi usare JSONArray obj = new JSONArray(json);. Quindi puoi usare un ciclo for per scorrere l'array.
— Phil

2
@FranciscoCorralesMorales usa solo un blocco try-catch . Se uno fallisce, presumi l'altro.
— Phil

1
@ ripDaddy69 Sembra che non sia un JSON non valido. Prevede accoppiamenti chiave-valore racchiusi tra parentesi graffe. Prova qualcosa di simile {"Fat cat":"meow"}.
— Phil

2
@Phil Questo non sembra essere un'assegnazione di stringa java valida. Non capisco cosa sto facendo diversamente sebbene JSONObject obj = new JSONObject ("Fat cat": "meow"); L'ho capito, avevo bisogno di usare \ davanti alle virgolette, e poi le virgolette effettive intorno all'intera cosa. Grazie.

31

il suo lavoro

    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
Anche se questo risponde alla domanda, non spiega perché o come funziona. Si prega di aggiungere una tale spiegazione.
— CerebralFart

Sembra una semplice soluzione di codice, che richiede la creazione di un altro oggetto che gestisce la sequenza di escape.
— kelalaka

7

prova questo:

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

2
cosa succede se la stringa è un array di oggetti JSON? Come "[{}, {}, {}]"
— Francisco Corrales Morales

Questa è una buona idea. La virgoletta singola funziona ed elimina la necessità di caratteri di escape.
— david m lee

1
Apostrophe potrebbe funzionare, in JAVA, ma non è strettamente legale JSON. Quindi potresti dover fare le cose in modo diverso in altre lingue o situazioni.
— Jesse Chisholm

4

Per ottenere un JSONObject o JSONArray da una stringa ho creato questa classe:

public static class JSON {

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

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

Qui per ottenere il 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);
}

Esempio:

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

Potresti semplicemente testare il primo carattere della stringa JSON per vedere se è [o {per sapere se è un array o un oggetto. Allora non rischieresti entrambe le eccezioni, solo quella pertinente.
— Jesse Chisholm

3

provalo, finalmente funziona per me:

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

Hai solo bisogno delle righe di codice come di seguito:

 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

Ecco il codice e puoi decidere quale
StringBuffer (sincronizzato) o StringBuilder più veloce usare.

Il benchmark mostra che StringBuilder è più veloce.

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

Può essere sotto è meglio.

JSONObject jsonObject=null;
    try {
        jsonObject=new JSONObject();
        jsonObject.put("phonetype","N95");
        jsonObject.put("cat","wp");
        String jsonStr=jsonObject.toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.