'How send Array to REST-Service (Jersey) with POST
i want to send an array of Locations to an REST-Service with JQuery.
My Code
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-Service
@POST
@Produces({ MediaType.APPLICATION_JSON })
@Path("{tripID}")
public Response addLocations(@PathParam("tripID") final String tripID, Location[] value) {
But i get an HTTP-500 Error. On the Server:
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)
Solution 1:[1]
I'm assuming it's because of the format you send the data in. Shouldn't the data you post be the entire stringified JSON? (including value which normally should be location?)
What I mean is that Jersey uses different JSON notations to serialize/deserialize messages so if for example you use MAPPED notation you should send something like:
{"location":[
{"alt":1,"lat":2,"long":3,"time":4},
{"alt":5,"lat":6,"long":7,"time":8}
]}
which means code like this with jQuery:
$.ajax({
data : JSON.stringify(
{"location" : [
{ alt: 1, lat: 2, long: 3, time: 4 },
{ alt: 5, lat: 6, long: 7, time: 8 }
]}),
....
For a NATURAL notation you should send:
[
{"alt":1,"lat":2,"long":3,"time":4},
{"alt":5,"lat":6,"long":7,"time":8}
]
which means code like:
$.ajax({
data : JSON.stringify(
[
{ alt: 1, lat: 2, long: 3, time: 4 },
{ alt: 5, lat: 6, long: 7, time: 8 }
]),
...
A fast way to see the default behaviour is to add this to your service and see what format it returns:
@GET
@Produces({ MediaType.APPLICATION_JSON })
@Path("/testNotation")
public Location[] getLocations() {
return new Location[] { new Location(), new Location() };
}
See here for some extra information:
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bogdan |
