122

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.

Syscall
  • 19,327
  • 10
  • 37
  • 52
sarath
  • 3,181
  • 7
  • 36
  • 58

9 Answers9

263

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 + "\"");
}
firelynx
  • 30,616
  • 9
  • 91
  • 101
Phil
  • 35,852
  • 23
  • 123
  • 164
  • 6
    what if the string is an array of JSON objects? Like "[{},{},{}]" – Francisco Corrales Morales Jun 17 '14 at 23:18
  • 3
    @FranciscoCorralesMorales you can use `JSONArray obj = new JSONArray(json);`. Then you can use a *for-loop* to iterate through the array. – Phil Jun 18 '14 at 01:59
  • ok, but what if the JSON can be an array or a single object ? JSONArray fails to do so. – Francisco Corrales Morales Jun 18 '14 at 02:29
  • 3
    @FranciscoCorralesMorales just use a *try-catch* block. If one fails, assume the other. – Phil Jun 18 '14 at 14:44
  • @Phil This does not appear to work if I change json to "Fat cat" or any other simple string like that. What is going on? I just pass to the catch block. –  May 26 '15 at 22:38
  • 1
    @ripDaddy69 It sounds like that is invalid JSON. It expects key-value pairings surrounded by curly brackets. Try something like `{"Fat cat":"meow"}`. – Phil May 27 '15 at 14:29
  • 2
    @Phil That doesn't appear to be a valid java String assignment. I don't understand what I am doing differently though JSONObject obj = new JSONObject("Fat cat":"meow"); I figured it out, I needed to use \ infront of the quotes, and then actual quotes around the whole thing. Thanks. –  May 27 '15 at 18:12
  • Not Working for me – Kamal Oberoi Jul 07 '16 at 11:05
  • @tobyyeats Can you please give an example of how you used \ and passed {"Fat cat":"meow"} to JSONObject ? – Neha Jul 11 '18 at 09:23
  • i want to convert this "{"abc":"10"}" and get both values individual. – Arbaz.in Mar 19 '20 at 13:29
41

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 + "\"");
    }
Serkan Hekimoglu
  • 4,234
  • 5
  • 40
  • 64
Ercan ILIK
  • 423
  • 4
  • 4
8

try this:

String json = "{'phonetype':'N95','cat':'WP'}";
Saro Taşciyan
  • 5,210
  • 5
  • 31
  • 50
user3139217
  • 89
  • 1
  • 1
8

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());
    }
Benson Githinji
  • 559
  • 7
  • 10
6

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);
mhKarami
  • 844
  • 11
  • 16
5

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;
    }
}
RiccardoCh
  • 1,060
  • 1
  • 13
  • 24
  • You could just test the first character of the JSON string to see if it is `[` or `{` to know whether it is an array or an object. Then you wouldn't be risking both exceptions, just the pertinent one. – Jesse Chisholm Sep 07 '18 at 15:51
  • @JesseChisholm if you're sure that the string is a well formatted json array you can do what you say, otherwise you could risk and exception. – RiccardoCh Oct 19 '22 at 13:59
1

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) {
    }
Thiago
  • 12,778
  • 14
  • 93
  • 110
0

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();
            }
        }
android.dk
  • 19
  • 1
  • 8
0

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();
    }
shaojun lyu
  • 184
  • 1
  • 6