I am building a RESTful web-service in Java using Jersey 1.11, and have problems implementing a method which consumes a list of JSON-ised entities. The single instance method works fine.
The error I get is:
Status 400 - Bad Request. The request sent by the client was syntactically incorrect.
My method signature looks like this:
@POST
@Path("/some-path/{someParam}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String createBatch(List<MyEntity> myEnts, @PathParam("someParam") String someParam)
{
...
}
The JSON I am sending in the requests is an array of MyEntity
JSON objects:
[{"field1" : value1, "field2" : value2}, {"field1" : value3, "field2" : value4}, ...]
Similar questions have been asked before and one straight forward suggestion was to change the consumed media type to text and de-serialize the JSON manually but I'd prefer a cleaner solution.
Is the JSON I am sending even valid in this context or do I need a top-level {}
i.e a wrapper entity? This would also seem a bit un-natural.
Thank you,
/David
Ok, so in the end I solved this using a simple wrapper class in order to generate
{ items : [{ <myEnityInstanceJson1> }, { <myEnityInstanceJson2> }, ... ]}
. I guess there is a way to have a generic wrapper but for now this will do:I think PathParam and also a Param which should unmarshalled by Jersey(JAX-RS) is not possible. Please try to remove the PathParam Parameter.
And if you need the second Parameter so create a new class like this
and also modify your Methode :
your JSON Should look like this:
Wrapper class works.
MyEntity[] myEnts
doesn't work.This is what I did and it worked.
Use
ObjectMapper
to convert to List of objects.The problem is the generic list type, which is not available at runtime due to type erasure, so Jersey wont know what kind of POJOs to unmarshal.
I think the simplest solution (which I know works, at least when using Jackson in your
MessageBodyReader
) in this case would be to just use a normal Java array instead of the List, so the method signature becomes:And yes, combining
@PathParam
and a consumed/unmarshalled body parameter should be fine.This is valid JSON for an array:
(see here for an example)
You don't need to send text, you can send it as JSON. Also your
MyEntity
should have@XmlRootElement
on it (see here, section 5.2 for an example).You don't need
PathParam
in your arguments,someParam
is available when the request is posted if you leave the@Path("/some-path/{someParam}")
in your method signature .