org.json.simple.JSONArray无法转换为org.json.simple.JSONObject
问题描述:
我正在尝试读取其中具有一系列整数数据的JSON文件,但是当读取时告诉我它无法从JSONObject转换为JSONArray
I'm trying to read a JSON file in which I have a series of integer data but when read tells me it can not convert from JSONObject to JSONArray
JSON文件结构的一部分是:
Part of the JSON file structure is:
{
"data": [
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 0, 0, 0, 0, 1, 1],
[1, 1, 0, 0, 0, 0, 1, 1],
[0, 1, 1, 0, 0, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]
],
"time": 0.2
},
代码:
public static void main(String[] args) throws InterruptedException {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("C:\\Carriots\\dos.json"));
JSONObject jsonObject = (JSONObject) obj;
// loop array
JSONArray tag = (JSONArray) jsonObject.get("data");
Iterator iterator = tag.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
答
您可以使用迭代器来处理数组数据.确保使用Object而不是String或Integer,因为将JSONObject转换为这些值之一时会出错.
You can use an iterator to process the array data. Be sure to use Object rather than String or Integer since you will get errors converting JSONObject to one of these values.
package jsonProcessing;
import java.io.FileReader;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonNumReader {
public static void main(String[] args) {
// TODO Auto-generated method stub
JSONParser parser = new JSONParser();
try {
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader("C:/JSON/numbers.json"));
JSONArray array = (JSONArray)jsonObject.get("data");
Iterator<Object>iterator = array.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
输出:
[1,1,1,1,1,1,1,1]
[1,1,0,0,0,0,1,1]
[1,1,0,0,0,0,1,1]
[0,1,1,0,0,1,1,0]
[0,1,1,1,1,1,1,0]
[0,0,1,1,1,1,0,0]
[0,0,0,0,0,0,0,0]
[0,0,0,0,0,0,0,0]