使用json-smart读取JSON文件 [英] Reading JSON file using json-smart

查看:507
本文介绍了使用json-smart读取JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将JSON文件中的值读取到数组以进行进一步处理。我正在使用JSON-Smart 1.2.0库。由于某些限制,我无法使用2.0版本。

I am trying to read the values from a JSON file to array for further processing. I am using JSON-Smart 1.2.0 library for the same. Due to some restrictions, I can not use the 2.0 version.

我收到以下异常。

java.lang.ClassCastException: net.minidev.json.JSONArray cannot be cast to net.minidev.json.JSONObject

我甚至尝试使用JSONArray而不是JSONObject。我在这做错了什么?这是读取json内容的正确方法吗?

I am even tried using JSONArray instead of JSONObject. What I am doing wrong over here? Is this correct way to read json content?

以下是java代码。

JSONObject json = (JSONObject) JSONValue.parseWithException(browsers);
JSONArray array = (JSONArray) json.get("friends");

for (int i = 0; i < array.size(); i++) {
    JSONObject cap = (JSONObject) array.get(i);
    String first = (String) cap.get("name");
    System.out.println(first);
}

以下是json文件内容。

Below is the json file content.

[
  {
    "friends": [
      {
        "id": 0,
        "name": "test1"
      },
      {
        "id": 1,
        "name": "test2"
      }
    ]
  }
]


推荐答案

您的JSON包含一个数组,它有一个单独的对象元素,所以你应该解析它:

Your JSON contains an array which has one single object element so you should parse it like that:

JSONArray root = (JSONArray) JSONValue.parseWithException(json);
JSONObject rootObj = (JSONObject) root.get(0);
JSONArray array = (JSONArray) rootObj.get("friends");

for (int i = 0; i < array.size(); i++) {
    JSONObject cap = (JSONObject) array.get(i);
    String first = (String) cap.get("name");
    System.out.println(first);
}

如果它可以有更多元素添加for循环而不是 root.get(0)

If it can have more elements add a for loop instead of root.get(0).

这篇关于使用json-smart读取JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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