users@jersey.java.net

[Jersey] reply: How to deserialize JSON to JAVA object?

From: joey.lv <joey.lv_at_7road.com>
Date: Fri, 31 Oct 2014 15:20:24 +0800

sorry,

the client code is error, the correct client code is :
$.ajax({
    url:"webapi/editUser",
    type:"POST",
    dataType:"json",
    contentType:'application/json; charset=utf-8',
    data:JSON.stringify( {
        "id":"112",loginName":"admin"
    }),
    success:function(result){
        console.log(result);
    }
});





发件人: joey.lv
发送时间: 2014-10-30 11:40
收件人: users
主题: [Jersey] How to deserialize JSON to JAVA object?
Jersey version : 2.13
I post a JSON data to the RESTful service, ant hope Jersey will auto deserialize this JSON data to a JAVA object.

Here is the client code:
$.ajax({
    url:"webapi/editUser",
    type:"POST",
    dataType:"json",
    dataObject:{
        "id":"112",loginName":"admin"
    },
    success:function(result){
        console.log(result);
    }
});


here is pom.xml
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
</dependency>


here is web.xml:
<!-- Jersey Servlet config -->
<servlet>
    <servlet-name>com.demo.rest.MyApplication</servlet-name>
</servlet>
<servlet-mapping>
    <servlet-name>com.demo.rest.MyApplication</servlet-name>
    <url-pattern>/webapi/*</url-pattern>
</servlet-mapping>


here is com.demo.rest.MyApplication.java:
@Path("webapi")
public class MyApplication extends ResourceConfig {
    public MyApplication(){
        register(MyResource.class);
    }
}


here is MyResource.class:
@POST
@Path("/editUser")
@Consumes(MediaType.APPLICATION_JSON)
public String editUser(User user) {
    logger.entry();
    System.out.println("user.id:" + user.getId());
    logger.exit();
    return "OK"
}


here is User.java:
@XmlRootElement
public class User implements Serializable {
    private Integer id;
    private String loginName;
    //setter;
    //getter;
}



Howerver, when the client post the JSON data to service, the User object parameter in editUser() always is null....