泽西岛,如何POST一个JSON对象列表? [英] Jersey, how to POST a list of JSON objects?
问题描述
我正在使用Jersey 1.11在Java中构建RESTful Web服务,并且在实现一个消耗JSON-ised实体列表的方法时遇到了问题。单实例方法工作正常。
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.
我得到的错误是:
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)
{
...
}
我在请求中发送的JSON是一个 MyEntity
JSON对象的数组:
The JSON I am sending in the requests is an array of MyEntity
JSON objects:
[{"field1" : value1, "field2" : value2}, {"field1" : value3, "field2" : value4}, ...]
以前曾提出类似的问题,一个直接的建议是将消费的媒体类型更改为文本并反序列化 JSON手动但我更喜欢更清洁的解决方案。
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.
我发送的JSON是否在t中有效他的上下文还是我需要顶级 {}
,即包装器实体?这看起来有点不自然。
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.
谢谢,
/ David
推荐答案
我认为PathParam以及一个应该由Jersey(JAX-RS)解组的Param是不可能的。
请尝试删除PathParam参数。
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
@XmlRootElement(name = "example")
public class Example {
@XmlElement(name = "param")
private String param;
@XmlElement(name = "entities")
private List<MyEntity> entities;
}
并修改你的Methode:
and also modify your Methode :
@POST
@Path("/some-path")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String createBatch(Example example)
{
...
}
你的JSON应该是这样的:
your JSON Should look like this:
{
"param":"someParam",
"entities":[
{"field1" : value1, "field2" : value2}, {"field1" : value3, "field2" : value4}, ...]
}
这篇关于泽西岛,如何POST一个JSON对象列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!