在REST post jersy中使用Json

时间:2015-06-09 06:16:29

标签: json web-services rest jaxb jersey

我正在尝试在rest服务中使用json对象,并将其转换为本地bean pojo jaxb类并将其用于进一步处理。

这是我的网络服务代码:

@POST
@Path("login1")
@Consumes(MediaType.APPLICATION_JSON)
public String login1(LoginJSON data)
{   
    try
    {
        System.out.println("request received for user"+data.username);
        System.out.println("pass: "+data.password);

    } catch (Exception e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return "success";
}

这是pojo类:

@XmlRootElement
public class LoginJSON
{
    @XmlElement(required=true) 
    public String username;

    @XmlElement(required=true) 
    public String password;

    public LoginJSON()
    {
        super();
        // TODO Auto-generated constructor stub
    }
    public LoginJSON(String username, String password)
    {
        super();
        this.username = username;
        this.password = password;
    }
    public String getUsername()
    {
        return username;
    }

    @XmlElement
    public void setUsername(String username)
    {
        this.username = username;
    }

    public String getPassword()
    {
        return password;
    }

    @XmlElement
    public void setPassword(String password)
    {
        this.password = password;
    }
}

web.xml是:

<servlet>
    <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer
    </servlet-class>
   <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name> 
      <param-value>com.myapp.webservices</param-value>
   </init-param>
   <load-on-startup>1</load-on-startup>
 </servlet> 

Webservice客户端正在发送一个带有user和password属性的json对象。我得到的错误是:

INFO: No default constructor found on class 
com.myapp.webservices.LoginJSON
java.lang.NoSuchMethodException: com.myapp.webservices.LoginJSON.<init>()
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getDeclaredConstructor(Unknown Source)
at com.sun.xml.internal.bind.v2.ClassFactory.create0(Unknown Source)

...

如何解决此问题?

2 个答案:

答案 0 :(得分:1)

删除LoginJSON类

中使用的构造函数

public LoginJSON() { super(); // TODO Auto-generated constructor stub } public LoginJSON(String username, String password) { super(); this.username = username; this.password = password; } 让类使用默认构造函数,否则json不会被解析为LoginJSON。

答案 1 :(得分:0)

在java中处理JSON的最简单的库是org.json, 你不需要POJO课程:

@POST
@Path("login1")
@Consumes(MediaType.APPLICATION_JSON)
public String login1(LoginJSON data) { 

    JSONObject dataJSON = new JSONObject(data);
    String username = dataJSON.get("username").toString();
    String password = dataJSON.get("password").toString();

    //...
    return "success";
}