conversion from string to JSON object Android

282,605

Solution 1

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

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

try this:

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

Solution 4

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

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);
Share:
282,605

Related videos on Youtube

sarath
Author by

sarath

Updated on February 19, 2022

Comments

  • sarath
    sarath about 2 years

    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.

    • tiguchi
      tiguchi almost 11 years
      I guess the offending character is a backslash because of your substitution. Why exactly are you doing that? Where does the JSON string come from?
    • sarath
      sarath almost 11 years
      I am getting the string from html..not as json
    • tiguchi
      tiguchi almost 11 years
      Just remove mystring= mystring.replace("\"", "\\\""); and see if it works for you then.
  • Francisco Corrales Morales
    Francisco Corrales Morales almost 10 years
    what if the string is an array of JSON objects? Like "[{},{},{}]"
  • Francisco Corrales Morales
    Francisco Corrales Morales almost 10 years
    what if the string is an array of JSON objects? Like "[{},{},{}]"
  • Phil
    Phil almost 10 years
    @FranciscoCorralesMorales you can use JSONArray obj = new JSONArray(json);. Then you can use a for-loop to iterate through the array.
  • Francisco Corrales Morales
    Francisco Corrales Morales almost 10 years
    ok, but what if the JSON can be an array or a single object ? JSONArray fails to do so.
  • Phil
    Phil almost 10 years
    @FranciscoCorralesMorales just use a try-catch block. If one fails, assume the other.
  • Admin
    Admin almost 9 years
    @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.
  • Phil
    Phil almost 9 years
    @ripDaddy69 It sounds like that is invalid JSON. It expects key-value pairings surrounded by curly brackets. Try something like {"Fat cat":"meow"}.
  • Admin
    Admin almost 9 years
    @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.
  • CerebralFart
    CerebralFart about 8 years
    While this does answer the question, it doesn't explain why or how it works. Please add such an explanation.
  • Kamal Oberoi
    Kamal Oberoi almost 8 years
    Not Working for me
  • david m lee
    david m lee almost 8 years
    This is a good idea. The single quote works and it eliminates the need for the escape characters.
  • Neha
    Neha almost 6 years
    @tobyyeats Can you please give an example of how you used \ and passed {"Fat cat":"meow"} to JSONObject ?
  • Jesse Chisholm
    Jesse Chisholm over 5 years
    Apostrophe might work, in JAVA, but it isn't strict legal JSON. So you may need to do things differently in other languages or situations.
  • Jesse Chisholm
    Jesse Chisholm over 5 years
    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.
  • Arbaz.in
    Arbaz.in about 4 years
    i want to convert this "{"abc":"10"}" and get both values individual.
  • kelalaka
    kelalaka almost 4 years
    It seems a simple code solution, that requires creating another object that handles the escape sequence.