如何从json对象获取字符串列表 [英] How to get list of strings from json object

查看:316
本文介绍了如何从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;
}

但是我找不到找到此部分的方法[getTheListOfMyFields].有什么建议吗?

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

推荐答案

您可以从访问错误数组的相同方式访问字段数组,而不是从JSON对象获取List<String>:

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(json, errorsIndex, fieldIndex) {
    JSONObject errorJson = json.getJSONArray("errors").getJSONObject(errorIndex);
    String value = errorJson.getJSONArray("fields").getString(fieldIndex);
    return value;
}

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

Note that get(fieldIndex) has changed to getString(fieldIndex). That way you don't have to cast an Object to a String.

这篇关于如何从json对象获取字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆