conversion from string to JSON object Android

AndroidJsonString ConversionJsonexception

Android Problem Overview


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.

Android Solutions


Solution 1 - Android

Remove the slashes:

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

Solution 2 - Android

This method works

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

Solution 3 - Android

try this:

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

Solution 4 - Android

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

Solution 5 - Android

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

Solution 6 - Android

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

Solution 7 - Android

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) {
    }

Solution 8 - Android

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

Solution 9 - Android

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsarathView Question on Stackoverflow
Solution 1 - AndroidPhilView Answer on Stackoverflow
Solution 2 - AndroidErcan ILIKView Answer on Stackoverflow
Solution 3 - Androiduser3139217View Answer on Stackoverflow
Solution 4 - AndroidBenson GithinjiView Answer on Stackoverflow
Solution 5 - AndroidmhKaramiView Answer on Stackoverflow
Solution 6 - AndroidRiccardoChView Answer on Stackoverflow
Solution 7 - AndroidThiagoView Answer on Stackoverflow
Solution 8 - Androidandroid.dkView Answer on Stackoverflow
Solution 9 - Androidshaojun lyuView Answer on Stackoverflow