Conversión de cadena a json objeto android
Estoy trabajando en una aplicación de Android. En mi aplicación tengo que convertir una cadena de objetos Json, a continuación, analizar los valores. Comprobé una solución en stackoverflow y encontré un problema similar aquí enlace
La solución es así
- Iterate Json datos del servicio web en el orden correcto
- Verificar firma digital en Android
- ¿Cómo utilizar BLOB con JSON y PHP?
- Android obtener json matriz anidados en el array
- Android JSon error "Esperaba BEGIN_OBJECT pero era BEGIN_ARRAY en la línea 1 columna 2"
`{"phonetype":"N95","cat":"WP"}` JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
Utilizo la misma manera en mi código. Mi cadena 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);
Estoy recibiendo la siguiente excepción json
org.json.JSONException: Expected literal value at character 1 of
Por favor, ayúdame a resolver mi problema.
- Generar listview desde JSON en android
- Android Json y valores nulos
- Cómo extraer el valor de la API
- Imágenes de Picasso Library y GridView
- Nullpointerexception al intentar obtener json array o json object de json string
- ¿Cómo se calcula el tiempo del rezo musulmán en una aplicación androide?
- Android Volley método de eliminación, ¿por qué enviar parámetros vacíos
- ProgressDialog o ProgressBar ralentiza la aplicación que ejecuta Android 4.1
Quite 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 + "\""); }
prueba esto:
String json = "{'phonetype':'N95','cat':'WP'}";
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 + "\""); }
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; } }
Aquí está el código, y usted puede decidir qué
(Sincronizado) StringBuffer o StringBuilder más rápido para 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(); } }
- ¿Es posible usar proguard en el modo de depuración?
- Ciclo de vida del fragmento – ¿Qué método se llama mostrar / ocultar?