2013-02-15 97 views
2

我想使用JQuery將位置數組發送到REST服務。如何使用POST將數組發送到REST服務(澤西島)

我的代碼

var locations = new Array(); 
var loc = new Location(); 
loc.alt = 0; 
loc.lat = 0; 
loc.long = 0; 
loc.time = 1; 

locations.push(loc); 

var json_data = {value : JSON.stringify(locations)}; 
console.log(json_data); 

$.ajax({type: 'POST', 
     url: rootURL + '/Location/123', 
     crossDomain: true, 
     dataType: "json", // data type of response 
     contentType: "application/json; charset=utf-8", 
     data: json_data, 
     success: function(data, textStatus, jqXHR) { 
      console.log('testAddLocations erfolgreich'); 
     }, 
     error: function(jqXHR, textStatus, errorThrown) { 
      console.log('testAddLocations Fehler'); 
     } 
    }); 

REST的服務

@POST 
@Produces({ MediaType.APPLICATION_JSON }) 
@Path("{tripID}") 
public Response addLocations(@PathParam("tripID") final String tripID, Location[] value) { 

,但我得到一個HTTP-500錯誤。在服務器上:

SCHWERWIEGEND: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container 
JsonFormatException{text=v, line=1, column=1} 
at com.sun.jersey.json.impl.reader.JsonLexer.yylex(JsonLexer.java:662) 
at com.sun.jersey.json.impl.reader.JsonXmlStreamReader.nextToken(JsonXmlStreamReader.java:162) 

回答

0

我猜想這是因爲格式的你發送的數據應該不是數據後,你是整個字符串化JSON? (包括value通常情況下應該location?)

我的意思是,澤西使用不同JSON notations序列化/反序列化消息,因此例如,如果你使用映射表示法的,你應該向這樣的:

{"location":[ 
    {"alt":1,"lat":2,"long":3,"time":4}, 
    {"alt":5,"lat":6,"long":7,"time":8} 
]} 

這是指這樣的代碼使用jQuery:

$.ajax({ 
    data : JSON.stringify( 
    {"location" : [ 
     { alt: 1, lat: 2, long: 3, time: 4 }, 
     { alt: 5, lat: 6, long: 7, time: 8 } 
    ]}), 
    .... 

一個自然的符號,你應該送:

[ 
    {"alt":1,"lat":2,"long":3,"time":4}, 
    {"alt":5,"lat":6,"long":7,"time":8} 
] 

這意味着類似的代碼:

$.ajax({ 
    data : JSON.stringify( 
    [ 
     { alt: 1, lat: 2, long: 3, time: 4 }, 
     { alt: 5, lat: 6, long: 7, time: 8 } 
    ]), 
    ... 

快速路上看到的默認行爲是添加到您的服務,看看它返回什麼樣的格式:

@GET 
@Produces({ MediaType.APPLICATION_JSON }) 
@Path("/testNotation") 
public Location[] getLocations() { 
    return new Location[] { new Location(), new Location() }; 
} 

在這裏看到一些額外信息:

http://jersey.java.net/nonav/documentation/latest/json.html
http://jersey.java.net/nonav/apidocs/1.17/jersey/com/sun/jersey/api/json/JSONConfiguration.html
http://jersey.java.net/nonav/apidocs/1.17/jersey/com/sun/jersey/api/json/JSONConfiguration.Notation.html
http://tugdualgrall.blogspot.ro/2011/09/jax-rs-jersey-and-single-element-arrays.html