Ganesh Hegde
Ganesh Hegde

Reputation: 227

How to send a JSON response in Spring?

I want to return a JSON response from the server in a spring application. Following is my code snippet.

@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 I'm getting an error client-side.

Upvotes: 4

Views: 11245

Answers (4)

dsk
dsk

Reputation: 657

//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

  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

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

               var app=jQuery.parseJSON(response);

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

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

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

Upvotes: 0

Khush
Khush

Reputation: 853

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 Jackson library in the class path so that Objects can be converted to JSON.

@ResponseBody tells spring to convert its return value and write it to the HTTP Response automatically. There is no other configuration required.

Upvotes: 2

SmartTechie
SmartTechie

Reputation: 123

The sample *-servlet.xml configuration is given below.

<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.

The detailed post explaining about the spring REST is available at http://smarttechie.org/2013/08/11/creating-restful-services-using-spring/

Upvotes: 0

Kiran
Kiran

Reputation: 20313

You need to:

  • Add Jackson JSON Mapper to the classpath
  • Add <mvc:annotation-driven> to your config
  • Return Map<Integer, String>

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

Upvotes: 2

Related Questions