2016-08-24 67 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!