[英]Parsing nested json array in java
我有以下格式的json文件。
{
"data":[
{
"prjId": 1,
"name" : "Forj1",
"issue": [
{
"id": 00001,
"status" : "Closed"
},
{
"id": 00002,
"status" : "Open"
}
]
},
{
"prjId": 2,
"name" : "Forj2",
"issue": [
{
"id": 00003,
"status" : "Closed"
},
{
"id": 00004,
"status" : "Open"
}
]
}],
"issueCounter": 7,
"success": true
}
這里的“數據”是項目的數組,在項目屬性中是“問題”的數組。
到目前為止,如果我刪除“問題”數組,則可以在“數據”屬性中向下遍歷json,如果此json具有“問題”數組,我會收到一條錯誤消息,說缺少逗號。
javax.json.stream.JsonParsingException: Invalid token=NUMBER at (line no=15, column no=14, offset=242) Expected tokens are: [COMMA]
下面是我現在擁有的代碼。 我對此有兩個問題,一個是在放置“ issue”屬性時讀取錯誤,其次是讀取“ issue”數組並遍歷其中所有屬性的方法。
InputStream fis = new FileInputStream(pathToFile+"data3.json");
JsonReader jsonReader = Json.createReader(fis);
//the error is thrown on below line while reading the above json.
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();
fis.close();
System.out.println(jsonObject.getInt("issueCounter"));
//reading arrays from json
JsonArray jsonArrayData = jsonObject.getJsonArray("data");
Project [] prj = new Project[jsonArrayData.size()];
int index = 0;
for(JsonValue value : jsonArrayData){
JSONObject jsonObj = new JSONObject(value.toString());
System.out.println(jsonObj.getString("name"));
System.out.println(jsonObj.getInt("prjId"));
//this is also the place where I am stuck, I know I need to construct an array out of it by obtaining issue attribute. Below is very very wrong.
/*
JsonArray jsonArrayIssue = jsonObj.getJsonArray("issue");
for(JsonValue issue : jsonArrayIssue){
JSONObject jsonIssueObj = new JSONObject(issue.toString());
System.out.println(jsonIssueObj.getString("status"));
System.out.println(jsonIssueObj.getInt("id"));
}
*/
}
任何幫助或指示深表感謝。 如果最終需要,我可以調整json,我需要維護一系列問題。
正如其他人所說,問題是JSON。 “ id”:00001 <-這是一個數字,根據JSON標准,數字不能以前導零開頭。 如果您控制JSON,則應對其進行調整。
或者,如果您不這樣做,則可以使用不太嚴格的解析器,例如org.json.simple
https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple 。代碼與您的代碼相同,剛剛調整為org.json.simple
try { ...
JSONObject rootJSON = (JSONObject) new JSONParser().parse(jsonString);
JSONArray dataList = (JSONArray) rootJSON.get("data");
for(Object projectObj: dataList.toArray()){
JSONObject project = (JSONObject)projectObj;
JSONArray issueList = (JSONArray) project.get("issue");
for(Object issueObj: issueList.toArray()){
JSONObject issue = (JSONObject) issueObj;
//do something with the issue
}
}
} catch (ParseException e) {
//do smth
e.printStackTrace();
}
您的json數據無效。您可以在此處檢查。 http://jsonlint.com
...issue": [{ "id": 00001,
"status": ----------------------^...issue": [{ "id": 00001,
您的ID必須是字符串數字,字符串,布爾值。發送1,2,3,....為返回值並檢查它是否有效。
"status": ----------------------^
您的代碼看起來不錯,問題在於JSON格式。 具體來說,以下幾行:
“ id”:00001,“ id”:00002,“ id”:00003,“ id”:00004,
基本上,如果您希望使用這種格式,則需要通過將值用引號引起來將它們設置為字符串,即“ id”:“ 00001”,或者可以使用有效數字即“ id”:1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.