我拉JSON格式的RESTful API並遍歷節點檢索我正在尋找的信息。但是有一個特定節點始終以「null」開頭,即使JSON文檔看起來不錯,並且該特定節點不包含任何空值。Tracksing JSON with Jackson總是返回null爲一個特定的節點
我是使用傑克遜解析JSON文檔的新手,我找不到爲什麼特定節點總是在節點值前返回「null」?
我遇到問題的節點是StationName
,它返回例如nullHägerstensåsen:
。我希望檢索的結果是沒有「null」的Hägerstensåsen:
。
從RESTful服務的原始JSON文件:
{
"Departure": {
"xmlnsxsi": "http://www.w3.org/2001/XMLSchema-instance",
"xmlnsxsd": "http://www.w3.org/2001/XMLSchema",
"xmlns": "http://www1.sl.se/realtidws/",
"LatestUpdate": "2014-01-21T11:34:36.7189974+01:00",
"ExecutionTime": "00:00:00.0937512",
"Buses": {},
"Metros": {
"Metro": [
{
"SiteId": "9262",
"TransportMode": "METRO",
"StationName": "Hägerstensåsen",
"GroupOfLine": "Tunnelbanans röda linje",
"DisplayRow1": "14 Fruängen 2 min",
"DisplayRow2": "14 Fruängen 12 min, 14 Fruängen 23 min"
},
{
"SiteId": "9262",
"TransportMode": "METRO",
"StationName": "Hägerstensåsen",
"GroupOfLine": "Tunnelbanans röda linje",
"DisplayRow1": "14 Mörby centrum 2 min.",
"DisplayRow2": "14 Mörby centrum 12 min. 14 Mörby centrum 22 min."
}
]
},
"Trains": {},
"Trams": {},
"TrainError": {
"HasError": "true",
"FaultCode": "Client",
"ErrorLevel": "Error",
"ErrorCode": "1000",
"ErrorSource": "/realtidws/RealTimeService.asmx/GetDepartures",
"ErrorMessage": "Connection string is missing"
},
"TramError": {
"HasError": "true",
"FaultCode": "Client",
"ErrorLevel": "Error",
"ErrorCode": "1000",
"ErrorSource": "/realtidws/RealTimeService.asmx/GetDepartures",
"ErrorMessage": "Connection string is missing"
}
}
}
我解析節點代碼:
...
result = null;
JsonNode node = mapper.readTree(slRealTimeClient.getJson(depatureSite));
node = node.path("Departure").path("Metros").path("Metro");
JsfUtil.debug("Node size: " + node.size());
depatureSiteResponse = node.get(0).path("SiteId").getTextValue();
for (JsonNode element : node) {
if (!element.isNull()) {
result += element.get("StationName").getTextValue();
result += ":" + System.getProperty("line.separator");
result += element.get("DisplayRow1").getTextValue();
result += System.getProperty("line.separator");
result += element.get("DisplayRow2").getTextValue();
result += System.getProperty("line.separator");
}
}
嘗試打印出的原始REST響應,或檢查在調試器的字符串。我有一種感覺,那裏可能會有一些額外的不可打印的字符,這些字符正在破壞事物。 – CodeChimp
我的猜測是,這與JSON無關,而是實際的字符數據。您有可能轉換爲JSON的8字節表示形式/不指定UTF8代碼頁,或實際上可能在StationName字符串中嵌入了不可見字符。 (提示:使用toString轉儲Metro陣列的元素。) –
@CodeChimp JSON文檔是未加處理的。 「@Hot舔」是的,這是我認爲,一個無形的字符。正如你所說,也許只是得到整個陣列並按原樣打印。 – Chris