簡體   English   中英

如何在 Spring 中發送 JSON 響應?

[英]How to send a JSON response in Spring?

我想在 spring 應用程序中從服務器返回一個 JSON 響應。 以下是我的代碼片段。

@RequestMapping(value="getCustomer.action", method = RequestMethod.GET)
    public @ResponseBody Customer getValidCustomer(Model model) {
        System.out.println("comes");
        Customer customer2 = (Customer) customerService
                .getCustomer("vvmnbv@jgfj.ghfjg");
        System.out.println(customer2.getEmail());
        return customer2;

    }

但是我在客戶端遇到錯誤。

你需要:

  • Jackson JSON Mapper添加到類路徑
  • <mvc:annotation-driven>到您的配置中
  • 返回Map<Integer, String>

閱讀: http : //blog.safaribooksonline.com/2012/03/28/spring-mvc-tip-returning-json-from-a-spring-controller/

由於您已經有了一些具體內容的答案,因此我想我只會提供一個示例。 干得好:

    @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);
}

只是一個小總結:如您所知,您將需要類路徑中的 Jackson 庫,以便對象可以轉換為 JSON。

@ResponseBody 告訴 spring 轉換其返回值並自動將其寫入 HTTP 響應。 不需要其他配置。

下面給出了示例 *-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>

然后將應用程序部署到服務器並通過將“Accept”標頭設置為“application/json”以獲取 JSON 格式的響應或“application/xml”以獲取 XML 格式的響應來發送請求。

有關 Spring REST 的詳細解釋可在http://smarttechie.org/2013/08/11/creating-restful-services-using-spring/ 獲得

//我創建了一個用於將簡單字符串轉換為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()+"\",";
}    }

//控制器代碼忽略我放入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 代碼

               var app=jQuery.parseJSON(response);

                $("#pid").html(app.PatientId);

                $("#pname").html(app.PatientName);

                $("#pcontact").html(app.Contact);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM