androidarraysjsonrestname-value

Need help formatting a JSON array


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

Solution

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