我想使用json simple库在java中读取这个JSON
文件。
我的JSON
文件长这样:
[
{
"name":"John",
"city":"Berlin",
"cars":[
"audi",
"bmw"
],
"job":"Teacher"
},
{
"name":"Mark",
"city":"Oslo",
"cars":[
"VW",
"Toyata"
],
"job":"Doctor"
}
]
这是我编写的Java代码,用于读取此文件:
package javaapplication1;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JavaApplication1 {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("c:\\file.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
System.out.println(name);
String city = (String) jsonObject.get("city");
System.out.println(city);
String job = (String) jsonObject.get("job");
System.out.println(job);
// loop array
JSONArray cars = (JSONArray) jsonObject.get("cars");
Iterator<String> iterator = cars.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
但是我收到了以下异常:
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject at javaapplication1.JavaApplication1.main(JavaApplication1.java:24)
有人能告诉我我做错了什么吗?整个文件都是一个数组,其中包含对象和另一个数组(cars)。但我不知道如何将整个数组解析成java数组。我希望有人能帮我补充我代码中缺失的代码行。
谢谢
List<YOUR_USER_MODEL> info = new Gson().fromJson(YOUR_JSON_STRING, new TypeToken<List<YOUR_USER_MODEL>>() {}.getType())
- Mostafa Nazari