我只是想从我的服务器向客户端返回一个JSON对象(使用ajax) – 所以我能够在客户端读取数据
@GET
@Produces("application/json")
@Consumes("application/json")
@Path("/getStatus/")
public void getStatus(
@Context HttpServletRequest request,
@Context HttpServletResponse response) throws servletexception,
IOException
{
//create the JSON Object to pass to the client
JSONObject object=new JSONObject();
response.setContentType("text/javascript");
try
{
object.put("name", nameDataFromClass);
object.put("status",someData);
}
catch(Exception e)
{
throw new servletexception("JSON Hosed up");
}
String json = object.toString();
response.getoutputStream().println(json);
}
<html>
<head>
<!-- Calls in jQuery file -->
<script src="jquery.js"></script>
<title>JQuery Test</title>
<script>
$.getJSON("http://localhost:8080/scout/rest/admin/mamba/getStatus",
function(json)
{
alert("Server naame: " + json.name);
});
</script>
</head>
<body>
</body>
</html>
解决方法:
Jackson库应该负责将json对象编组到您的对象,反之亦然.只需创建一个简单的POJO,如下所示:
public class Mystatus{
public String name;
public String status;
public Mystatus(){} // a default empty constructor is needed
public Mystatus(String name,String status){
this.name=name;
this.status=status;
}
}
然后从RESTful Web服务返回此对象:
@GET
@Produces("application/json")
@Consumes("application/json")
@Path("/getStatus/")
public Mystatus getStatus(
@Context HttpServletRequest request,
@Context HttpServletResponse response)
{
response.setContentType("text/javascript");
return new Mystatus("Hello","World");
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。