【问题标题】:Spring MVC Custom Converter for JSON data not workingJSON数据的Spring MVC自定义转换器不起作用
【发布时间】:2013-10-04 15:52:48
【问题描述】:

我正在创建一个测试应用程序,以在传递给控制器​​之前实现从 JSON 字符串到员工对象的转换。

这里是执行的关键步骤

  • Employee.java 类的创建:域对象
  • EmployeeManagementController.java 类的创建:用于管理员工的 Spring MVC 控制器
  • EmployeeConverter.java 的创建:用于将 JSON 字符串转换为 Employee 对象的自定义转换器。
  • 创建employee-servlet.xml:Spring配置文件
  • web.xml 的创建:部署描述符

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

}

还定义了其他域对象

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




}

员工-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>

我正在使用 Firefox RestClient 对其进行测试。

这是正确映射到 Employee 对象的 JSON。

{"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}]}}

没有抛出异常,并且控制器确实在 addEmployee() 方法中接收到 Employee 对象。但它不是通过转换器。转换器没有被调用。我不知道为什么?我不想使用初始化活页夹或@Valid。我想知道我哪里出错了。如何使它工作?

【问题讨论】:

  • 首先,在@Component&lt;bean&gt; 声明之间进行选择。不要同时使用。
  • 对不起,我会改变,更大的问题是如何使转换器被调用。

标签: java json spring spring-mvc typeconverter


【解决方案1】:

您将 Spring 使用 Converters 和 ConversionService 的通用类型转换支持与其对 HTTP 消息转换的支持混淆了,后者专门用于转换 Web 请求和响应并理解媒体类型(如您正在使用的 application/json) . HTTP 消息转换使用 HttpMessageConverter 实例。

在这种情况下,您实际上不需要自定义转换器。 Spring 的 MappingJacksonHttpMessageConverter 用于自动执行转换。转换可以自动执行,因为大概(您还没有发布 setter,所以我做出有根据的猜测),Employee 中的 setter 方法与 JSON 匹配,即 setName、setAge、setPhoneNumber 等。

可以说,您拥有的代码已经在工作。您可以安全地删除您的自定义转换器,拥有相同的功能,并且需要维护的代码更少。如果您真的想使用自定义转换器,则需要实现 HttpMessageConverter 并在 MappingJacksonHttpMessageConverter 之前/代替 MappingJacksonHttpMessageConverter 进行配置。

【讨论】:

  • 感谢 Andy 揭开了消息转换器之间差异的神秘面纱。 Spring Spring 源代码在定义 Web 参数解析器、InitBinders 和属性编辑器、类型转换器、消息转换器和格式化程序之间的明确界限方面已经失去了作用。但这也让我定义了我的实际需求。这只是一个 PoC,我可以在需要自定义转换的情况下应用转换器。我认为 Message Converter 是我真正需要的应用程序。
  • 在我们的实际应用程序中,我们试图实现 JSON 到 PDF 的直接转换,即 JSON 将被解析为自定义对象,如 Document,这些对象又包含对 Itext 对象的引用。问题是几个 Itext bean 没有 getter 和/或 setter,如果我直接尝试将 JSON 映射到 itext 对象,这会导致 Jackson Parser 抛出异常。为此,我需要创建一个中间 TemplateMapper 自定义对象,该对象执行必要的复制到 Itext 对象,所以我不能在没有任何转换器的情况下继续进行,或者如您在此处所说的消息转换器。你能提供任何资源吗?
  • 这可能最好在单独的问题中处理。您可能希望注册一个自定义 HttpMessageConverter,或者自定义 Spring 用于自动转换的 Jackson ObjectMapper。
  • 好吧,我已经应用了这两种方法,扩展 ObjectMapper 效果不佳。它导致无限递归循环导致堆栈溢出异常。这是因为我在覆盖它时从 parse() 方法中调用了 super.readValue()。我知道 readValue() 本身会调用 parse() 方法并导致无限的 recursion。无论如何,扩展 HttpMessageConverter 确实为我创造了奇迹。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2012-09-16
  • 2018-03-25
  • 2022-08-03
  • 2022-09-26
  • 2021-08-28
  • 1970-01-01
  • 2012-09-10
  • 2016-11-24
相关资源
最近更新 更多