conversion from string to JSON object Android
Asked Answered
I

9

123

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.

Invasion answered 12/8, 2013 at 17:17 Comment(3)
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?Windpollinated
I am getting the string from html..not as jsonInvasion
Just remove mystring= mystring.replace("\"", "\\\""); and see if it works for you then.Windpollinated
S
264

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 + "\"");
}
Sankhya answered 12/8, 2013 at 17:24 Comment(10)
what if the string is an array of JSON objects? Like "[{},{},{}]"Rubel
@FranciscoCorralesMorales you can use JSONArray obj = new JSONArray(json);. Then you can use a for-loop to iterate through the array.Sankhya
ok, but what if the JSON can be an array or a single object ? JSONArray fails to do so.Rubel
@FranciscoCorralesMorales just use a try-catch block. If one fails, assume the other.Sankhya
@Sankhya 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.Streusel
@ripDaddy69 It sounds like that is invalid JSON. It expects key-value pairings surrounded by curly brackets. Try something like {"Fat cat":"meow"}.Sankhya
@Sankhya 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.Streusel
Not Working for meCooksey
@tobyyeats Can you please give an example of how you used \ and passed {"Fat cat":"meow"} to JSONObject ?Wacke
i want to convert this "{"abc":"10"}" and get both values individual.Diminutive
H
43

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 + "\"");
    }
Heffron answered 14/5, 2016 at 20:39 Comment(2)
While this does answer the question, it doesn't explain why or how it works. Please add such an explanation.Mogilev
It seems a simple code solution, that requires creating another object that handles the escape sequence.Knowhow
T
8

try this:

String json = "{'phonetype':'N95','cat':'WP'}";
Torpedo answered 13/3, 2014 at 10:22 Comment(3)
what if the string is an array of JSON objects? Like "[{},{},{}]"Rubel
This is a good idea. The single quote works and it eliminates the need for the escape characters.Hegumen
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.Berthold
F
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());
    }
Fourscore answered 6/7, 2018 at 11:1 Comment(0)
E
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);
Exarchate answered 21/1, 2019 at 14:8 Comment(0)
M
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;
    }
}
Messene answered 28/9, 2016 at 8:10 Comment(2)
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.Berthold
@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.Messene
B
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) {
    }
Buffington answered 20/2, 2021 at 0:14 Comment(0)
I
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();
            }
        }
Infectious answered 9/2, 2015 at 11:28 Comment(0)
C
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();
    }
Crabb answered 14/12, 2017 at 6:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.