在Java中读取JSON对象中的字符串数组
我有一个JSON对象,看起来像这样在Java中读取JSON对象中的字符串数组,java,json,Java,Json,我有一个JSON对象,看起来像这样 { "students": [ { "Name": "Some name", "Bucket": 4, "Avoids": ["Foo", "Bar"] }, { "Name": "Some other name", "Bucket": 1, "Avoids": ["Some String"] } ] } 我试图用Java解析这个JSON对象 以下
{
"students": [
{
"Name": "Some name",
"Bucket": 4,
"Avoids": ["Foo", "Bar"]
},
{
"Name": "Some other name",
"Bucket": 1,
"Avoids": ["Some String"]
}
]
}
我试图用Java解析这个JSON对象
以下是我的Java代码:
Object obj = parser.parse(new FileReader("./data.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray students = (JSONArray) jsonObject.get("students");
Iterator<JSONObject> studentIterator = students.iterator();
while (studentIterator.hasNext()) {
JSONObject student = (JSONObject) studentIterator.next();
String name = (String) student.get("Name");
double bucketValue;
if (student.get("Bucket") instanceof Long) {
bucketValue = ((Long) student.get("Bucket")).doubleValue();
} else {
bucketValue = (double) student.get("Bucket");
}
JSONArray avoids = (JSONArray) student.get("Avoids");
Iterator<JSONObject> avoidsIterator = avoids.iterator();
while (avoidsIterator.hasNext()) {
String s = (String) avoidsIterator.next();
}
}
我知道
error: incompatible types: JSONObject cannot be converted to String
这是意料之中的。但我确信数组中的所有值都是字符串。我怎样才能得到所有这些字符串
也有避免数组为空的实例。我不明白为什么这样做不起作用
String s = avoidsIterator.next().toString();
将Avoid迭代器更改为字符串的迭代器,而不是JsonObject的迭代器
这会编译,但会产生错误:java.lang.String不能强制转换为org.json.simple.JSONObject这很奇怪,因为该代码不会尝试在任何地方将字符串强制转换为JSONObject。您的代码中是否还有其他地方可以执行该转换?我的代码没有更改。我的评论是指@toltman的代码行。
String s = avoidsIterator.next().toString();
Iterator<String> avoidsIterator = avoids.iterator();
while (avoidsIterator.hasNext()) {
String s = avoidsIterator.next();
System.out.println(s);
}
Foo
Bar
Some String