Spring MVC Custom Converter for JSON data not working

RaghaveShukla

I am creating a test application to to achieve conversion from JSON String to Employee Object before being passed to the controller.

Here are the key steps performed

  • Creation of Employee.java Class : Domain Object
  • Creation of EmployeeManagementController.java class : Spring MVC Controller for Managing Employee
  • Creation of EmployeeConverter.java : Custom Converter for Converting JSON String to Employee Object.
  • Creation of employee-servlet.xml : Spring Configuration file
  • Creation of web.xml : The Deployment Descriptor

Employee.java

package com.bluebench.training.domain;

import org.springframework.stereotype.Component;

@Component("employee")
public class Employee {

    private PersonalDetail personal;
    private EducationDetail education;
    private WorkExperienceDetail experience;


    // Getters and Setters

}

other domain objects are also defined

EmployeeManagementController.java

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bluebench.training.domain.Employee;

@Controller
public class EmployeeManagementController {

    @RequestMapping(value="/ems/add/employee",method=RequestMethod.POST,consumes="application/json",produces="application/json")
    public @ResponseBody int addEmployee(@RequestBody Employee emp){
        System.out.println("RAGHAVE");
        System.out.println(emp.getPersonal().getName());
        int empId = 20;
        return empId;
    }




}

EmployeeConverter.java

package com.bluebench.training.converter;

import java.io.IOException;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.core.convert.converter.Converter;

import com.bluebench.training.domain.Employee;

public class EmployeeConverter implements Converter<String,Employee>{

    @Override
    public Employee convert(String json) {
        System.out.println("Inside convert()");
        Employee emp = null;
        try {
            emp = new ObjectMapper().readValue(json,Employee.class);
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }           
        return emp;
    }




}

employee-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>

            <beans xmlns="http://www.springframework.org/schema/beans"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
                xmlns:context="http://www.springframework.org/schema/context"
                xmlns:mvc="http://www.springframework.org/schema/mvc"
                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="com.bluebench.training"/>

                <mvc:annotation-driven  conversion-service="conversionService"/>

                <mvc:default-servlet-handler/>          

                <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
                    <property name="mediaTypes">
                        <map>
                            <entry key="json" value="application/json" />
                            <entry key="xml" value="text/xml" />
                            <entry key="htm" value="text/html" />
                        </map>
                    </property>
                    <property name="defaultContentType" value="text/html"/>
                </bean>

                <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
                    <property name="converters">
                        <list>
                            <bean class="com.bluebench.training.converter.EmployeeConverter"/>
                        </list>
                    </property>
                </bean>

            </beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>PROJECT_38_SpringMVCRESTFul</display-name>

  <servlet>
    <servlet-name>employee</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  <servlet-name>employee</servlet-name>
  <url-pattern>/*</url-pattern>
  </servlet-mapping>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/employee-servlet.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>



</web-app>

I am using Firefox RestClient to Test it.

Here is the JSON which correctly maps to the Employee object.

{"personal":{"name":"Raghave","age":33,"phoneNumber":"9594511111","address":"101, software appartment, software land , mumbai"},"education":{"qualifications":[{"insititute":"Amity University","degree":"Bachelor of Science","yearOfPassing":"2007","percentage":62.0}]},"experience":{"experience":[{"companyName":"QTBM","designation":"Programmer","years":3,"salary":12000.0},{"companyName":"Polaris","designation":"Software Developer","years":1,"salary":24000.0},{"companyName":"Ness","designation":"Senior Software Engineer","years":2,"salary":50000.0},{"companyName":"JPMC","designation":"Senior Applications Developer","years":1,"salary":120000.0}]}}

There is no Exception thrown and the controller does receive the Employee Object in the addEmployee() method. But its not via converter. The Converter is not invoked. I dont know why ? I dont want to use init binders or @Valid. I wanted to know where am i going wrong. how to make it work?

Andy Wilkinson

You've confused Spring's general type conversion support that uses Converters and the ConversionService with its support for HTTP message conversion that is specifically designed for converting web requests and responses and understands media types (like application/json that you're using). HTTP message conversion uses instance of HttpMessageConverter.

You don't actually need a custom converter in this case. Spring's MappingJacksonHttpMessageConverter is being used to perform the conversion automatically. The conversion can be performed automatically because, presumably (you haven't posted the setters so I'm making an educated guess), the setter methods in Employee match the JSON, i.e. setName, setAge, setPhoneNumber etc.

Arguably, the code that you've got is already working. You can safely delete your custom converter, have the same functionality, and have less code to maintain. If you really want to use a custom converter, you'll need to implement HttpMessageConverter and configure it before/in place of MappingJacksonHttpMessageConverter.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Custom WinForms data binding with converter not working on nullable type (double?)

From Dev

JSON data binding in spring mvc

From Dev

Custom Struts type converter is not working

From Dev

Custom Struts type converter is not working

From Dev

Spring Cache Abstraction & custom converter

From Dev

Spring Data Rest - Custom Json Schema / Alps?

From Dev

Create a custom NewtonSoft JSon Converter

From Dev

Setting a custom json converter for DocumentDb

From Dev

Custom generic json converter not called

From Dev

Spring MVC - Returning JSON Object with List<Custom> property

From Dev

Spring MVC internationalization not working

From Dev

@Range not working in spring mvc

From Dev

SwaggerSpringMvcPlugin not working on Spring MVC

From Dev

OpenEntityManagerInViewFilter not working - Spring MVC

From Dev

logout not working in spring mvc

From Dev

Custom HttpMessageConverter in Spring MVC

From Dev

Spring MVC custom validators

From Dev

how to insert json data to the database from json response in spring mvc

From Dev

Why does Spring MVC report "No converter found for return value of type: class org.json.JSONObject"?

From Dev

Spring Boot MVC Converter Cannot Autowire Neo4J Data Repositories

From Dev

Spring-Data-MongoDB: Failed to convert from type after upgrade to 2.0.7 with custom converter

From Dev

Custom json converter json.net

From Dev

Custom JSON converter not being called after posting data from ajax to controller

From Dev

Spring MVC: Not able to submit form data in JSON format

From Dev

Can I use JSON data in RequestMapping in Spring MVC

From Dev

get pathvariable with sending and recieving json data Rest spring mvc

From Dev

Spring MVC how to handle Joda Data Types as JSON

From Dev

Spring Send JSON data via HTTP POST not working

From Dev

Json.net Custom enum converter

Related Related

  1. 1

    Custom WinForms data binding with converter not working on nullable type (double?)

  2. 2

    JSON data binding in spring mvc

  3. 3

    Custom Struts type converter is not working

  4. 4

    Custom Struts type converter is not working

  5. 5

    Spring Cache Abstraction & custom converter

  6. 6

    Spring Data Rest - Custom Json Schema / Alps?

  7. 7

    Create a custom NewtonSoft JSon Converter

  8. 8

    Setting a custom json converter for DocumentDb

  9. 9

    Custom generic json converter not called

  10. 10

    Spring MVC - Returning JSON Object with List<Custom> property

  11. 11

    Spring MVC internationalization not working

  12. 12

    @Range not working in spring mvc

  13. 13

    SwaggerSpringMvcPlugin not working on Spring MVC

  14. 14

    OpenEntityManagerInViewFilter not working - Spring MVC

  15. 15

    logout not working in spring mvc

  16. 16

    Custom HttpMessageConverter in Spring MVC

  17. 17

    Spring MVC custom validators

  18. 18

    how to insert json data to the database from json response in spring mvc

  19. 19

    Why does Spring MVC report "No converter found for return value of type: class org.json.JSONObject"?

  20. 20

    Spring Boot MVC Converter Cannot Autowire Neo4J Data Repositories

  21. 21

    Spring-Data-MongoDB: Failed to convert from type after upgrade to 2.0.7 with custom converter

  22. 22

    Custom json converter json.net

  23. 23

    Custom JSON converter not being called after posting data from ajax to controller

  24. 24

    Spring MVC: Not able to submit form data in JSON format

  25. 25

    Can I use JSON data in RequestMapping in Spring MVC

  26. 26

    get pathvariable with sending and recieving json data Rest spring mvc

  27. 27

    Spring MVC how to handle Joda Data Types as JSON

  28. 28

    Spring Send JSON data via HTTP POST not working

  29. 29

    Json.net Custom enum converter

HotTag

Archive