Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get list of strings from 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 "fields" the following way:

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?

like image 446
lenka Avatar asked Aug 18 '15 20:08

lenka


1 Answers

Instead of getting a List<String> from the JSON Object, you can access the array of fields in the same way you are accessing the array of errors:

public static String getField(JSONObject json, String errorsIndex, String 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). That way you don't have to cast an Object to a String.

like image 173
gla3dr Avatar answered Oct 14 '22 01:10

gla3dr