如何从我的休息服务发送 json 对象,以便我可以在客户端 javascript 解析输入
我只是想从服务器返回一个 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);
}
这将在 JSP 的客户端中我想提取页面上的数据
<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>
I just simply want to return a JSON object (using ajax) from my server to the client side - so I'm able to read the data in the client side
@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);
}
This would be in the client side for JSP I want to extract the data out on the page
<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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Jackson 库应该负责将 json 对象编组到您的对象,反之亦然。只需创建一个简单的 POJO,如下所示:
然后从 RESTful Web 服务返回此对象:
The Jackson library should take care of marshalling json objects to your objects, and vice versa. Just create a simple POJO, like this:
Then return this object from your RESTful webservice:
index.jsp
index.jsp