-3

I have this array for my web service : {"update":true,"msg":"Logged in Bro","role":"admin"}

Now, I need to use this in Android to work around my application beyond login. So what I need here is a way to format this data into namevaluepairs or individual variables so that I can use them.

I am currently using this but it force closes my application :

try {

            JSONObject jsonRootObject = new JSONObject(result);

            //Get the instance of JSONArray that contains JSONObjects
            JSONArray jsonArray = jsonRootObject.optJSONArray("");

            //Iterate the jsonArray and print the info of JSONObjects
            for(int i=0; i < jsonArray.length(); i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                update = jsonObject.optString(jsonObject.optString("update").toString());
                message = jsonObject.optString("msg").toString();
                role = jsonObject.optString(jsonObject.optString("role").toString());


            }

        } catch (JSONException e) {e.printStackTrace();}

2 Answers2

1

To parse the JSON you provided you need something like this:

   JSONObject jsonObject = new JSONObject(jsonString);

   update = jsonObject.optBoolean("update");
   message = jsonObject.optString("msg");
   role = jsonObject.optString("role");
Gennadii Saprykin
  • 4,505
  • 8
  • 31
  • 41
1

I assume result contains your JSON as a String:

{"update":true,"msg":"Logged in Bro","role":"admin"}

Therefore,

JSONObject jsonRootObject = new JSONObject(result);

creates a JSON object with three properties, update, msg and role. You can access them like this:

boolean update = jsonRootObject.optBoolean("update");
String msg = jsonRootObject.optString("msg");
String role = jsonObject.optString("role");

Your code crashes on jsonArray.length() because jsonArray == null: jsonRootObject.optJSONArray(""); returns null as there is no array with the key "" within your object.


optString("msg").toString();

is illogical in itself. optString either returns a String or null. Your code will crash if the property msg is not present. If you expect a property to be present, use getString instead of optString. In general, don't call toString() on Strings.


jsonObject.optString(jsonObject.optString("role").toString());

does not make sense either. There is no key in your object which is equal to the value of the property role.

Tobias
  • 7,723
  • 1
  • 27
  • 44
  • I liked it how you descriptively explained the code to me. Really appreciate it. Had used and marked the above help already so could not mark yours as the right answer but this was great help and I hope people learn from this. Thanks. – Krishnakant Mishra Jul 15 '15 at 16:59