tutorialspoint studio read parser from example array android json string-conversion jsonexception

studio - conversión de cadena a objeto json android



read json from android studio (6)

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

La solución es así

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

Yo uso el mismo camino 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 ya que

{/"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);

Obtengo la siguiente excepción json

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

Por favor, ayúdame a resolver mi problema.


Aquí está el código, y usted puede decidir qué
(sincronizado) StringBuffer o StringBuilder más rápido de usar.

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


Eliminar las barras inclinadas:

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 + "/""); }


Para obtener un objeto 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 estar abajo 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(); }


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 + "/""); }


prueba esto:

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