自定义HttpMessageConverter接收JSON格式数据

Spring默认使用Jackson处理json数据,在实际开发中,也可以使用其他开源类包处理json数据.那么,如果使用其他的开源类包处理JSON,该如何配置HttpMessageConverter呢?接下来,我们就使用业界非常受欢迎的fastjson来接收json数据.
1.修改配置文件springmvc-config.xml
<!-- 配置annotation类型的处理器适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
            <list>
                <ref bean="fastJsonHttpMessageConverter" />
            </list>
        </property>
</bean>

<bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
    <!-- 加入支持的媒体类型:返回contentType -->
    <property name="supportedMediaTypes">
        <list>
            <value>text/html;charset=UTF-8</value>
            <value>application/json;charset=UTF-8</value>
        </list>
    </property>
 </bean>

2.控制器

package org.fkit.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.fkit.domain.Book;
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.fasterxml.jackson.databind.ObjectMapper;

@Controller
@ResponseBody
public class InterfaceController
{
    @RequestMapping(value="/interface/json2book",method=RequestMethod.POST,consumes = "application/json")
    
    public Object json2book(
            @RequestBody Book book,
            HttpServletResponse response
            ) throws Exception
    {
        System.out.println(book);
        System.out.println(book.getName());
        
        book.setAuthor("liulibo");
        Book book2 = new Book(100,"书名","作者");

        List<Book> list = new ArrayList<Book>();
        list.add(book);
        list.add(book2);
        
        return list;
    }
}