【发布时间】:2017-10-27 22:21:19
【问题描述】:
我有以下 JSONObject(不是数组,我不介意转换)。我正在尝试做两件事:
获取流派条目的计数为“诗歌”(计数 = 2)。
-
获取作者姓名和流派的键值:
- 作者名 = 马尔科姆
genreName = 新闻文章
作者名 = 济慈
- genreName = 诗歌
{ "AddressBook" :{
"Details" :{
"authorname" :{
"Author-malcolm":{
"genre" :"poetry"
}
"Author-keats":{
"genre" :"poetry"
}
}
}
}
}
我尝试过的代码:
public static void main(String[] args) throws Exception, IOException, ParseException {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("My path to JSON"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray arrayhere = new JSONArray();
arrayhere.add(obj);
System.out.println(arrayhere);
int count = 0;
for(int i = 0; i < arrayhere.size(); i++) {
JSONObject element = arrayhere.getJSONObject(i);//The method getJSONObject(int) is undefined for the type JSONArray
String branchName = element.getString("genre");//The method getString(String) is undefined for the type JSONObject
if(branchName.equals("poetry")) {
count ++;
}
}
System.out.println("Count f0r poetry genre=" + count);
}
}
我已经查看了所有解决方案。在 stackoverflow 上没有类似的问题。我不确定程序是否正确。
【问题讨论】: