2013-08-12 15 views
67

Sto lavorando su un'applicazione Android. Nella mia app devo convertire una stringa in Json Object, quindi analizzare i valori. Ho controllato per una soluzione in StackOverflow e ho trovato problema simile qui linkconversione da stringa a oggetto json android

La soluzione è come questo

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

io 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 sostituire 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);

io sono sempre l'eccezione JSON sotto

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

Si prega di aiuto io per risolvere il mio problema.

+0

Immagino che il personaggio incriminato sia un backslash a causa della tua sostituzione. Perché lo stai facendo esattamente? Da dove viene la stringa JSON? – tiguchi

+0

Sto ricevendo la stringa da html..not come jias – sarath

+1

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

risposta

156

Rimuovere 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 + "\""); 
} 
+1

Cosa succede se la stringa è una matrice di oggetti JSON? Come "[{}, {}, {}]" –

+3

@FranciscoCorralesMorales è possibile utilizzare 'JSONArray obj = new JSONArray (json);'. Quindi puoi usare un * for-loop * per scorrere l'array. – Phil

+0

ok, ma cosa succede se il JSON può essere un array o un singolo oggetto? JSONArray non riesce a farlo. –

7

provare questo:

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

Cosa succede se la stringa è una matrice di oggetti JSON? Mi piace "[{}, {}, {}]" –

+0

Questa è una buona idea. La singola citazione funziona ed elimina la necessità dei caratteri di escape. –

0

Ecco il codice, e si può decidere quale
(sincronizzato) StringBuffer o StringBuilder più veloce da 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(); 
      } 
     } 
10

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

Mentre questo risponde alla domanda, non spiega perché o come funziona. Per favore aggiungi questa spiegazione. – SZenC

4

Per ottenere un JSONObject o JSONArray da una stringa che 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 accedere al 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; 
    } 
} 
0

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