5

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?

3
  • Is getTheListOfMyFields supposed to be an index? Commented Aug 18, 2015 at 20:05
  • no, just a list of strings(List<String>): ["name", "address"] Commented Aug 18, 2015 at 20:08
  • At the end, you want value to be the element in the "fields" array at index fieldIndex, is that correct? So for example, if fieldIndex were 1, then value would be "address"? Commented Aug 18, 2015 at 20:09

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I thought JSONArray is an aray of json objects and it it not applicable here... haha =) Thanks a lot! =)
What the type of 'json' parameter, ha?
@DynoCris It's a JSONObject from the org.json package.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.