Web services JAX-RS—删除请求POST的json中的对象名(RootElement)

Web services JAX-RS—删除请求POST的json中的对象名(RootElement),web-services,rest,jakarta-ee,jaxb,jax-rs,Web Services,Rest,Jakarta Ee,Jaxb,Jax Rs,我将JAX-RS用于RESTful服务,当客户机(angularjs、soapui等)发出请求后,需要在json中添加对象名(根元素)。例如: @POST @Path("/create") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createUser (UserVo userVo){ ... ... } -- 客户端需要指定“userV

我将JAX-RS用于RESTful服务,当客户机(angularjs、soapui等)发出请求后,需要在json中添加对象名(根元素)。例如:

@POST
@Path("/create")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createUser (UserVo userVo){
    ...
    ...
}
--

客户端需要指定“userVo”(如果我从
userVo
中删除
@XmlRootElement
,则无法识别该对象),但我不想指定它来改进我的REST Api:

{
    email:"john@gmail.com",
    mobilePhone:1234456
}
如果未指定对象名称,则返回错误:

16:04:04278警告[http-bio-8080-exec-3]AbstractJAXBProvider:660- javax.xml.bind.UnmarshalException -带有链接的异常:[com.sun.istack.SAXParseException2;列号:0;elemento inesperado(URI:,本地:“电子邮件”)。Los 埃斯佩拉多斯森元素酒店

我找到的唯一方法是接收hashmap(客户端发送“
应用程序”\u FORM\u URLENCODED
”类型)并构建对象,但我认为效率较低

对JAX-RS有什么想法吗?可能吗

对于响应,我使用Gson并将对象返回到我想要的方式:

json = gson.toJson(userVo);
return Response.ok(json, MediaType.APPLICATION_JSON).build();
--


在post请求中发送负载时,不需要包括类名

JAX-RS是java提供的规范。第三方供应商,如Jersey、ApacheCXF、RestEasy和Restlets实现了JAX-RS

例如,如果使用Jersey,则使用Jersey moxy进行编组/解编。下面是pom.xml中moxy的依赖关系/从下载

API和UserVo保持原样

@POST
@Path("/create")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createUser (UserVo userVo){
    ...
    ...
}

@XmlRootElement
public class UserVo implements Serializable, Comparable<UserVo>{
    ...
    ...
}
@POST
@路径(“/create”)
@使用(MediaType.APPLICATION_JSON)
@产生(MediaType.APPLICATION_JSON)
公共响应createUser(UserVo UserVo){
...
...
}
@XmlRootElement
公共类UserVo实现了可序列化、可比较的{
...
...
}

现在,根据您的jax-rs实现,为封送/解封添加适当的库,代码应该可以工作。

谢谢,我在pom.xml中添加了jackson-JAXR,并且可以工作!太好了…很乐意帮忙。
json = gson.toJson(userVo);
return Response.ok(json, MediaType.APPLICATION_JSON).build();
{
    email:"john@gmail.com",
    mobilePhone:1234456
}
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
            <version>${jersey.version}</version>
        </dependency>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-jaxrs</artifactId>
    <version>1.1.1</version>
</dependency>
{
    "email":"john@gmail.com",
    "mobilePhone":"1234456"
}
@POST
@Path("/create")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createUser (UserVo userVo){
    ...
    ...
}

@XmlRootElement
public class UserVo implements Serializable, Comparable<UserVo>{
    ...
    ...
}