Java 如何在春季发送 Json 响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18780415/
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
How to send Json response in spring?
提问by Ganesh Hegde
I want to return json response from the server side using spring. My code is this.
我想使用 spring 从服务器端返回 json 响应。我的代码是这样的。
@RequestMapping(value="getCustomer.action", method = RequestMethod.GET)
public @ResponseBody Customer getValidCustomer(Model model) {
System.out.println("comes");
Customer customer2 = (Customer) customerService
.getCustomer("[email protected]");
System.out.println(customer2.getEmail());
return customer2;
}
But it is giving error in front end.enter code here
但它在前端出错。在此处输入代码
回答by Unknown
You need to:
你需要:
- Add Hymanson JSON Mapperto the classpath
- Add
<mvc:annotation-driven>
to your config - Return
Map<Integer, String>
- 将Hymanson JSON Mapper添加到类路径
- 添加
<mvc:annotation-driven>
到您的配置 - 返回
Map<Integer, String>
Read:http://blog.safaribooksonline.com/2012/03/28/spring-mvc-tip-returning-json-from-a-spring-controller/
阅读:http : //blog.safaribooksonline.com/2012/03/28/spring-mvc-tip-returning-json-from-a-spring-controller/
回答by SmartTechie
The sample *-servlet.xml configuration is given below.
下面给出了示例 *-servlet.xml 配置。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="org.smarttechies.controller" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="html" value="text/html"></entry>
<entry key="json" value="application/json"></entry>
<entry key="xml" value="application/xml"></entry>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
</bean>
</beans>
Then deploy the application into server and send the request by setting the “Accept” header to “application/json” to get the response in JSON format or “application/xml” to get the response in XML format.
然后将应用程序部署到服务器并通过将“Accept”标头设置为“application/json”以获取 JSON 格式的响应或“application/xml”以获取 XML 格式的响应来发送请求。
The detailed post explaining about the spring REST is available at http://smarttechie.org/2013/08/11/creating-restful-services-using-spring/
有关 Spring REST 的详细解释可在http://smarttechie.org/2013/08/11/creating-restful-services-using-spring/ 获得
回答by Khush
Since you already have an answer with some specifics in it I thought I would just contribute with an example. Here you go:
由于您已经有了一些具体内容的答案,因此我想我只会提供一个示例。干得好:
@RequestMapping(value = "/getfees", method = RequestMethod.POST)
public @ResponseBody
DomainFeesResponse getFees(
@RequestHeader(value = "userName") String userName,
@RequestHeader(value = "password") String password,
@RequestHeader(value = "lastSyncDate", defaultValue = "") String syncDate) {
return domainFeesHelper.executeRetreiveFees(userName, password, syncDate);
}
Just a little summary: As you know you will need the Hymanson library in the class path so that Objects can be converted to JSON.
只是一个小总结:如您所知,您将需要类路径中的 Hymanson 库,以便对象可以转换为 JSON。
@ResponseBody tells spring to convert its return value and write it to the HTTP Response automatically. There is no other configuration required.
@ResponseBody 告诉 spring 转换其返回值并自动将其写入 HTTP 响应。不需要其他配置。
回答by dsk
//I have created a class for converting simple string into json convertable format and returned it to the JSP page where it parsed into json and used like
//我创建了一个用于将简单字符串转换为json可转换格式的类并将其返回到JSP页面,在那里它解析为json并使用
public class Json {
public static String Convert(Object a,Object b){
return " \""+a.toString()+"\" : \""+b.toString()+"\",";
}
public static String ConvertLast(Object a,Object b){
return " \""+a.toString()+"\" : \""+b.toString()+"\" }";
}
public static String ConvertFirst(Object a,Object b){
return "{ \""+a.toString()+"\" : \""+b.toString()+"\",";
} }
//Controller code ignore the data that i put into the conver(),convertLast() and convertFirst() methods
//控制器代码忽略我放入conver()、convertLast()和convertFirst()方法的数据
String json = Json.ConvertFirst("apId", appointment.getId())
+ Json.Convert("appDate",
format.format(appointment.getAppointmentdate()))
+ Json.Convert("appStart", formathourse.format(appointment
.getAppointmentstarttime()))
+ Json.Convert("appEnd", formathourse.format(appointment
.getAppointmentendtime()))
+ Json.Convert("PatientId", appointment.getPatientId()
.getId())
+ Json.Convert("PatientName", appointment.getPatientId()
.getFname()
+ " "
+ appointment.getPatientId().getLname())
+ Json.Convert("Age", appointment.getPatientId().getAge())
+ Json.Convert("Contact", appointment.getPatientId()
.getMobile())
+ Json.Convert("Gender", appointment.getPatientId()
.getSex())
+ Json.ConvertLast("Country", appointment.getPatientId()
.getCountry());
return json;}
/JSP JQuery Code
/JSP JQuery 代码
var app=jQuery.parseJSON(response);
$("#pid").html(app.PatientId);
$("#pname").html(app.PatientName);
$("#pcontact").html(app.Contact);