How to get a list of strings from a json object

I have the following JSON:

{"errors":[{"code":888,"errorId":"xxx","message":"String value expected","fields":["name", "address"]}, {}, {}]} 

I want to be able to get the "fields" as follows:

 public static String getField(json, errorsIndex, fieldIndex) { JSONObject errorJson = json.getJSONArray("errors").getJSONObject(errorIndex); String value = errorJson.[getTheListOfMyFields].get(fieldIndex); return value; } 

But I can’t find a way to make this part [getTheListOfMyFields]. Any suggestion?

+4
source share
1 answer

Instead of getting a List<String> from a JSON object, you can access an array of fields the same way you access an array of errors:

 public static String getField(json, errorsIndex, fieldIndex) { JSONObject errorJson = json.getJSONArray("errors").getJSONObject(errorIndex); String value = errorJson.getJSONArray("fields").getString(fieldIndex); return value; } 

Note that get(fieldIndex) has changed to getString(fieldIndex) . Thus, you do not need to cast the object to a string.

+5
source

All Articles