android - 如何在 Android 中解析 JSON?

这个问题在这里已经有了答案:
关闭4年前

如何在 Android 中解析 JSON 提要?

最佳答案

Android 内置了解析 json 所需的所有工具。示例如下,不需要 GSON 或类似的东西。

获取您的 JSON:

假设你有一个 json 字符串

String result = "{\"someKey\":\"someValue\"}";

创建一个JSONObject :

JSONObject jObject = new JSONObject(result);

如果你的 json 字符串是一个数组,例如:

String result = "[{\"someKey\":\"someValue\"}]"

那么你应该使用如下所示的 JSONArray 而不是 JSONObject

获取特定字符串

String aJsonString = jObject.getString("STRINGNAME");

获取特定的 bool 值

boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");

获取特定整数

int aJsonInteger = jObject.getInt("INTEGERNAME");

获取特定的多头

long aJsonLong = jObject.getLong("LONGNAME");

获取特定的 double

double aJsonDouble = jObject.getDouble("DOUBLENAME");

获取具体JSONArray :

JSONArray jArray = jObject.getJSONArray("ARRAYNAME");

从数组中获取项目

for (int i=0; i < jArray.length(); i++)
{
    try {
        JSONObject oneObject = jArray.getJSONObject(i);
        // Pulling items from the array
        String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray");
        String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY");
    } catch (JSONException e) {
        // Oops
    }
}

https://stackoverflow.com/questions/9605913/

相关文章:

c# - ASP.NET Core 返回带有状态码的 JSON

python - json.load() 和 json.loads() 函数有什么区别

javascript - JSON.parse 意外字符错误

json - curl json 通过终端向 Rails 应用程序发布请求

javascript - 无法使用 "-"破折号访问 JSON 属性

json - 如何在 Swift 中解码 HTML 实体?

android - 如何在 Android 中使用 HTTPClient 以 JSON 格式发送 P

json - 如何在 ECMAScript 6 中导入 JSON 文件?

javascript - 如何使用 html 表单数据发送 JSON 对象

javascript - 从AngularJS中的对象数组中通过id获取特定对象