java 如何从json对象获取字符串列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32081648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:38:04  来源:igfitidea点击:

How to get list of strings from json object

javaarraysjsonlist

提问by lenka

I have the following JSON:

我有以下 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?

但是我找不到制作这部分 [getTheListOfMyFields] 的方法。有什么建议吗?

回答by gla3dr

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:

List<String>您可以像访问错误数组一样访问字段数组,而不是从 JSON 对象中获取 a :

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). That way you don't have to cast an Object to a String.

请注意,get(fieldIndex)已更改为getString(fieldIndex). 这样你就不必将对象转换为字符串。