Need help formatting a JSON array

167 Views Asked by At

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

There are 2 best solutions below

0
Gennadii Saprykin On BEST ANSWER

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");
1
Tobias On

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.