javascript Springs MVC JSON 响应并将其转换为 JS 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13228203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Springs MVC JSON Response and convert it to JS Object
提问by Ankur Jain
I am having a question that how can I send JSON Object from Springs MVC so that I can convert it into a JavaScript Object on my HTML Page.
我有一个问题,即如何从 Springs MVC 发送 JSON 对象,以便我可以将其转换为 HTML 页面上的 JavaScript 对象。
In a traditional way I do it: Below is a snippet from Java Servlet which sets a request attribute and forward it to the JSP Page.
我以传统的方式这样做:下面是 Java Servlet 的一个片段,它设置了一个请求属性并将其转发到 JSP 页面。
JSONObject jsonObj = new JSONObject();
jsonObj.put("name","test");
jsonObj.put("age",24);
request.setAttribute("jsonObj",jsonObj);
request.getRequestDispatcher("test.jsp").forward(request,response);
In JSP I retrieve as :
在 JSP 中,我检索为:
<script type="text/javascript">
var jsonObj =<%=request.getAttribute("jsonObj"); %>;
alert("name = "+jsonObj.name+" ; age = "+jsonObj.age); // This will output name and age from the JSON Object
</script>
So what I need to ask how can I do the same in Springs MVC. How can I send the JSONObject from Dispatcher Servlet, and convert it to JS object in my JSP page ?
所以我需要问我如何在 Springs MVC 中做同样的事情。如何从 Dispatcher Servlet 发送 JSONObject,并将其转换为 JSP 页面中的 JS 对象?
回答by derlinuxer
An easy way to do this using the ObjectMapper. It will create an JSON String from your Object. And that you can send to your view/jsp.
使用 ObjectMapper 执行此操作的简单方法。它将从您的对象创建一个 JSON 字符串。并且您可以发送到您的视图/jsp。
I put an small example of a controller I do this (just snipped).
我放了一个控制器的小例子我这样做了(只是剪掉了)。
@Controller
public class UsersSettingsController {
@Autowired
UserSettingsDefaultService userSettingsService;
@RequestMapping(value="/userSettings/dynamic/userSettings", method=RequestMethod.GET)
public ModelAndView get() throws Exception {
ModelAndView mav = new ModelAndView();
ObjectMapper mapper = new ObjectMapper();
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
UserSettings userSet = userSettingsService.getUserSettingsByUser(user);
mav.addObject("userSettingsJSON", mapper.writeValueAsString(userSet));
mav.setViewName("userSettings/dynamic/filter");
return mav;
}
}
Or course can you create your JSON Object in your Contoller step by step like you did in your example. Then you don't need the Mapper, just sending the String to your View.
或者,您可以像在示例中一样一步一步地在控制器中创建 JSON 对象。然后你不需要映射器,只需将字符串发送到你的视图。
In the JSP you load the json String like this into a JS var:
在 JSP 中,您将这样的 json 字符串加载到 JS 变量中:
var jsonString = '${userSettingsJSON}';
To get elements from JSON String or parse, see: http://www.json.org/js.html.
I'm an KnockOut Framework Fan would do it with it.
要从 JSON 字符串中获取元素或解析,请参阅:http: //www.json.org/js.html。
我是一个 KnockOut 框架的粉丝会用它来做。
回答by jinchuan
I think you should use ajax(for example jquery),the following is spring mvc
我认为你应该使用ajax(例如jquery),以下是spring mvc
@RequestMapping(value = "/admin/new/list", method = RequestMethod.GET)
@ResponseBody
public List<News> list()
{
return newsDao.findAll();
}
and in the jsp page,you may use ajax util (for example jquery)
在jsp页面中,你可以使用ajax util(例如jquery)
$.ajax({
type: "GET",
url: '<c:url value="/admin/new/list"/>',
cache:false,
dataType :'json',
success: function(data){
alert(data);
}
});
the data is json object I don't know whether the above is what you need
数据是json对象不知道上面是不是你需要的
回答by Gunjan Shah
As per your requirement, I suggest you to use AJAX call with JSON as data type.
根据您的要求,我建议您使用 JSON 作为数据类型的 AJAX 调用。
For example :
例如 :
$.ajax({
url: "getFormatIdDescMap?compId="+compId,
global: false,
type: "POST",
dataType:"json",
contanttype:'text/json',
async:false,
error:function(){
alert("Error during retrieving the foramt ID List");
},
success: function(data){
//REMOVE ALL THE OLD VALUES OF FORMAT DROP DOWN
removeDropDownVals('formatList');
var optn;
for(var index=0;index<data.formatKeys.length;index++){
optn = document.createElement("option");
document.getElementById("formatList").options.add(optn);
optn.text =data.formatDescs[index];
optn.value=data.formatKeys[index];
}
}
});
});
In the code above, I am preparing a new list of Formats based on company ID. You can iterate over the response.
在上面的代码中,我正在准备一个基于公司 ID 的新格式列表。您可以迭代响应。
It will give response text as per your requirements. But here note that .. if you are getting json Array in the response, it will contain that data in square bracket like..[1,2,3] and If you are getting response in JSON Object then it will be displayed in curly braces like {"data",[1,2,3]}.
它将根据您的要求提供响应文本。但在这里请注意,.. 如果您在响应中获得 json 数组,它将包含在方括号中的数据,如 ..[1,2,3] 并且如果您在 JSON 对象中获得响应,那么它将以卷曲显示像 {"data",[1,2,3]} 这样的大括号。
回答by david99world
A much easier way to do this is to include the Hymanson dependencies in maven and use @ResponseBody to return a JSON representation of the object, without having to manually write the manipulation.
一个更简单的方法是在 maven 中包含 Hymanson 依赖项,并使用 @ResponseBody 返回对象的 JSON 表示,而无需手动编写操作。
Have a look at the example below, you shouldn't have to write any tranlation to JSON code.
看看下面的例子,你不应该编写任何到 JSON 代码的翻译。
http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/
http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/