Java 使用 json-smart 读取 JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24185155/
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
Reading JSON file using json-smart
提问by Purus
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.
我正在尝试将 JSON 文件中的值读取到数组以进行进一步处理。我正在使用 JSON-Smart 1.2.0 库。由于某些限制,我无法使用 2.0 版本。
I am getting the following exception.
我收到以下异常。
java.lang.ClassCastException: net.minidev.json.JSONArray cannot be cast to net.minidev.json.JSONObject
I am even tried using JSONArray instead of JSONObject. What I am doing wrong over here? Is this correct way to read json content?
我什至尝试使用 JSONArray 而不是 JSONObject。我在这里做错了什么?这是读取 json 内容的正确方法吗?
Below is the java code.
下面是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);
}
Below is the json file content.
下面是json文件内容。
[
{
"friends": [
{
"id": 0,
"name": "test1"
},
{
"id": 1,
"name": "test2"
}
]
}
]
采纳答案by cy3er
Your JSON contains an array which has one single object element so you should parse it like that:
您的 JSON 包含一个具有单个对象元素的数组,因此您应该像这样解析它:
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);
}
If it can have more elements add a for loop instead of root.get(0)
.
如果它可以有更多元素添加一个 for 循环而不是root.get(0)
.