2016-08-24 58 views
0

我的Web服務中有幾個類,一個使用BookingTable對象,另一個使用包含一個BookingTable對象列表和一個bookingController類的包裝器來處理請求。從JavaScript發送對象列表到Spring Web服務導致空對象

BookingTable.java

package com.webservice; 

import java.util.List; 

public class BookingTable { 
    private String deskID; 
    private List<String> dates; 

    public BookingTable(){} 

    public void setDeskID(String id){ 
     this.deskID=id; 
    } 
    public String getDeskID(){ 
     return deskID; 
    } 
    public void setDates(List<String> dates){ 
     this.dates=dates; 
    } 
    public List<String> getDates(){ 
     return dates; 
    } 
} 

BookingTableWrapper.java

package com.webservice; 

import java.util.ArrayList; 
import java.util.List; 

public class BookingTableWrapper { 

    private List<BookingTable> bookingTables = new ArrayList<>(); 

    public BookingTableWrapper() {} 

    public List<BookingTable> getBookingTables() { 
     return bookingTables; 
    } 

    public void setBookingTables(List<BookingTable> bookingTables) { 
     this.bookingTables = bookingTables; 
    } 
} 

(部分)BookingController.java

@RequestMapping(value = "/test", method = RequestMethod.POST) 
public @ResponseBody ResponseEntity<String> test(@ModelAttribute BookingTableWrapper bookingTableWrapper) { 

    return ResponseEntity.ok("Hi"); 
} 

我送我在JavaScript AJAX請求是這樣的:

var bookingTableWrapper = 
      { 
       "bookingTables": [{ 
        "deskID": "1", 
        "dates": ["1", "2", "3"] 
       }, { 
        "deskID": "2", 
        "dates": ["4","5","6"] 
       }] 
      } 




    $.ajax({ 
     dataType: "json", 
     url:"http://localhost:8080/test", 
     method: "POST", 
     data: JSON.stringify(bookingTableWrapper) 
    }) 

該請求進入後端,但不創建對象。我只看到它是一個空對象。我試着用BookingTable對象,它工作正常,但是當我嘗試使用BookingTableWrapper時,我什麼也得不到。任何幫助將不勝感激。

Response containing empty object

Response/Request Headers and what's being posted in Firebug

+0

http請求和標題在firebug或chrome網絡標記或類似內容中的外觀如何? – jlumietu

+0

從休息客戶端發送你的JSON請求,並檢查你是否得到空對象。 – Vaibs

+0

我附上了一張以上的響應/請求標題 –

回答

0

我已經改變了控制器,這是建議的@Vaibs:

@RequestMapping(value = "/test", method = RequestMethod.POST) 
    public @ResponseBody ResponseEntity<String> test(@RequestBody BookingTableWrapper bookingTableWrapper) { 
    System.out.println("Element " +bookingTableWrapper.getBookingTables().get(0).getDeskID()); 
     return ResponseEntity.ok("Hi"); 
    } 

這給了一個錯誤:

NetworkError: 415 Unsupported Media Type - localhost:8080/test";

所以我加了一些標題標籤到我的AJAX請求,感謝this後。

$.ajax({ 
     headers: { 
      'Accept': 'application/json', 
      'Content-Type': 'application/json' 
     }, 
     dataType: "json", 
     url:"http://localhost:8080/test", 
     method: "POST", 
     data: JSON.stringify(bookingTableWrapper) 
    }) 

現在可以工作。 謝謝@Vaibs!