我正在尝试将 JSON 文件读入数据结构,以便可以计算一堆元素。
JSON 文件的格式为[{String, String, [], String } ... ]
. 现在在这个对象数组中,我需要找到第一个字符串字段(比如说关联)与数组字段(成员名称)的关系。我需要弄清楚每个成员所属的协会有多少。
我目前正在使用 json-simple,这就是我的做法。
Object obj = parser.parse(new FileReader("c://Users/James McNulty/Documents/School/CMPT 470/Ex 4/exer4-courses.json"));
JSONArray jsonArray = (JSONArray) obj;
ArrayList<JSONObject> courseInfo = new ArrayList<JSONObject>();
Iterator<JSONObject> jsonIterator = jsonArray.iterator();
while (jsonIterator.hasNext()) {
courseInfo.add(jsonIterator.next());
count++;
//System.out.println(jsonIterator.next());
}
//System.out.println(count);
String course = "";
String student = "";
ArrayList<JSONArray> studentsPerCourse = new ArrayList<JSONArray>();
for (int i=0; i<count; i++) {
course = (String) courseInfo.get(i).get("course");
studentsPerCourse.add((JSONArray) courseInfo.get(i).get("students"));
System.out.println(course);
System.out.println(studentsPerCourse.get(i));
}
ArrayList<String> students = new ArrayList<String>();
for (int i=0; i<count; i++) {
for (int j=0; j< (studentsPerCourse.get(i).size()); j++) {
students.add((String) studentsPerCourse.get(i).get(j));
//System.out.println(studentsPerCourse.get(i).get(j));
}
//System.out.println(student);
}
JSONObject object = new JSONObject();
Map<String, Integer> studentCourses = new HashMap<String, Integer>();
Set<String> unique = new HashSet<String>(students);
for (String key : unique) {
studentCourses.put(key, Collections.frequency(students, key));
object.put(key, Collections.frequency(students, key));
//System.out.println(key + ": " + Collections.frequency(students, key));
}
FileWriter file = new FileWriter("c://Users/James McNulty/Documents/School/CMPT 470/Ex 4/output.json");
file.write(object.toJSONString());
file.flush();
file.close();
System.out.print(object);
想知道 simple-json 本身是否有更简单的方法,或者是否有其他更好的库。