所以我试图使用这个json文件,但是当我尝试用JSONobject解析它时,它给了我错误。我试图找到类似的问题,但似乎人们没有同样的事情。
代码产生此错误消息
Exception in thread "main" org.json.JSONException:
A JSONObject text must begin with '{' at 1 [character 2 line 1]
爪哇:
public void readSubjects(String filename){
obj =new JSONObject(filename.trim());
objArr=obj.getJSONArray("subjects".trim());
String tmpName;
String tmpRealName;
for(int i=0;i<objArr.length();i++){
tmpName=objArr.getJSONObject(i).getString("subject_code");
tmpRealName=objArr.getJSONObject(i).getString("name");
System.out.println(tmpName + " " + tmpRealName);
}
}
JSON-文件:
{
"teachers": [
{
"name": [
"Peremann"
],
"age": 22,
"subject": [
"pgr200"
],
"availability": true,
"contact_info": ""
},
{
"name": "Jarand",
"age": 23,
"subject": "root"
}
],
"subjects": [
{
"subject_code": "pgr200",
"name": "Avansert Javaprogrammering",
"campus_priority": "Fjerdingen",
"educationForm": "",
"subjectProgram": "",
"duration": "X",
"amountOfHours": "",
"amountOfStudents": 12
}
],
"studentGroups": [
{
"students": []
}
],
"rooms": [
{
"room_code": "F11",
"fasilitetsstoette": "test",
"max-capasity": 50,
"room-size": "X"
}
]}
答案 0 :(得分:0)
这一行
obj =new JSONObject(filename.trim());
不正确。 JSONObject
的{{3}}需要一个实际的JSON字符串,不是文件的名称。
首先阅读文件的内容,然后将其传递给JSONObject
的构造函数。
String content = new String(Files.readAllBytes(Paths.get("example.json")));
obj = new JSONObject(content);
答案 1 :(得分:0)