我正在一個Java應用程序中嘗試從基於Spring-MVC的服務器獲取數據,並且當前是system.out它,但由於標記爲空而得到輸出。我打印出正在從服務器發送的代碼,這是正確的。我對REST沒有太多經驗,所以如果有人告訴我我做錯了什麼,我將不勝感激。Java:JsonPareser不包含任何數據
客戶機代碼:
public void getCanvas(){
JsonFactory jsonFactory = new JsonFactory();
String canvas = "";
try {
JsonParser jsonParser = jsonFactory.createJsonParser(new URL(canvasURL));
JsonToken token = jsonParser.nextToken();
while (token!=JsonToken.START_ARRAY){
token = jsonParser.nextToken();
System.out.println("Token is "+token);
}
while (token != JsonToken.END_ARRAY){
token = jsonParser.nextToken();
if(token == JsonToken.START_OBJECT){
canvas = jsonParser.toString();
// I also tried token.toString
System.out.println("Canvas is "+canvas);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
客戶機輸出:
Token is FIELD_NAME
Token is VALUE_NUMBER_INT
Token is FIELD_NAME
Token is VALUE_STRING
Token is FIELD_NAME
Token is VALUE_NUMBER_FLOAT
Token is FIELD_NAME
Token is VALUE_NULL
Token is FIELD_NAME
Token is VALUE_STRING
Token is FIELD_NAME
Token is VALUE_STRING
Token is FIELD_NAME
Token is VALUE_STRING
Token is FIELD_NAME
Token is VALUE_NULL
Token is FIELD_NAME
Token is VALUE_FALSE
Token is FIELD_NAME
Token is VALUE_NULL
Token is FIELD_NAME
Token is VALUE_NUMBER_INT
Token is END_OBJECT
即必須是已印刷ATLEAST 100倍。
Server代碼:
@RequestMapping(value = "/getcanvas",method = RequestMethod.GET)
public @ResponseBody String getCanvasforFX(){
System.out.println("Canvas was requested");
Canvas canvas = this.canvasService.getCanvasById(10650);
ObjectMapper objectMapper = new ObjectMapper();
try {
System.out.println("Canvas value is "+objectMapper.writeValueAsString(canvas));
return objectMapper.writeValueAsString(canvas);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
服務器輸出:
Canvas was requested
Canvas value is {"canvasid":10650,"canvasname":"Aks","canvasnumber":1.0,"canvastitle":null,"canvasdate":"","canvascreator":"","canvasiteration":"","canvasimage":"iVBORw0K5CYII=","canvasDisabled":false,"imageData":null,"person1id":7402}
什麼我做錯了,我想打印在客戶端受此畫布價值。
它終於奏效了。 –