[android] conversion from string to json object android

I am working on an Android application. In my app I have to convert a string to Json Object, then parse the values. I checked for a solution in stackoverflow and found similar issue here link

The solution is like this

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

I use the same way in my code . My string is

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

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

And after replace I got the result as this

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

when I execute JSONObject jsonObj = new JSONObject(mybizData);

I am getting the below json exception

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

Please help me to solve my issue.

This question is related to android json string-conversion jsonexception

The answer is


its work

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

try this:

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

You just need the lines of code as below:

   try {
        String myjsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
        JSONObject jsonObject = new JSONObject(myjsonString );
        //displaying the JSONObject as a String
        Log.d("JSONObject = ", jsonObject.toString());
        //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());
    }

May be below is better.

JSONObject jsonObject=null;
    try {
        jsonObject=new JSONObject();
        jsonObject.put("phonetype","N95");
        jsonObject.put("cat","wp");
        String jsonStr=jsonObject.toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }

just try this , finally this works for 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);

To get a JSONObject or JSONArray from a String I've created this class:

public static class JSON {

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

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

Here to get the 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);
}

Example:

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

Here is the code, and you can decide which
(synchronized)StringBuffer or faster StringBuilder to use.

Benchmark shows StringBuilder is Faster.

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

Using Kotlin

    val data = "{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"somename\",\"userName\":\"value\"},\"pendingPushDetails\":[]}\n"
    
try {
      val jsonObject = JSONObject(data)
      val infoObj = jsonObject.getJSONObject("ApiInfo")
    } catch (e: Exception) {
    }

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to string-conversion

conversion from string to json object android How to convert array to a string using methods other than JSON? convert a JavaScript string variable to decimal/money What is the difference between parseInt(string) and Number(string) in JavaScript?

Examples related to jsonexception

conversion from string to json object android