在spring mvc3中,已经集成了Jackson(json处理器)来处理数据输出json格式,spring中封装的类是 [color=blue]org.springframework.http.converter.json.MappingJackson2HttpMessageConverter[/color]这个json转换器, 如果是[color=red]springmvc3.2[/color]之前的版本,可以使用[color=blue]org.springframework.http.converter.MappingJacksonHttpMessageConverter[/color]这个json转换器。


[size=x-large][color=red]springmvc使用@ResponseBody返回json乱码解决方法[/color][/size] [url]http://www.itxxz.com/a/javashili/ask/2014/1222/501.html[/url]
[color=blue][b]1.springmvc 3.2以上的版本解决乱码的方法:[/b][/color]

[b]  第一步:在配置中加入:[/b]

<mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8" />
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                     <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                         <property name="failOnEmptyBeans" value="false" />
                     </bean>
                 </property>
            </bean>
        </mvc:message-converters>
     </mvc:annotation-driven>


或者可以这样写


<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="jsonRequestConverter" />
			</list>
		</property>
	</bean>
	<bean id="jsonRequestConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>




[b]  第二步:需要的加入的jackson jar如下:[/b]



<dependency>

        <groupId>com.fasterxml.jackson.core</groupId>

        <artifactId>jackson-annotations</artifactId>

        <version>2.1.0</version>

      </dependency>

      <dependency>

        <groupId>com.fasterxml.jackson.core</groupId>

        <artifactId>jackson-core</artifactId>

        <version>2.1.0</version>

      </dependency>

      <dependency>

        <groupId>com.fasterxml.jackson.core</groupId>

        <artifactId>jackson-databind</artifactId>

        <version>2.1.0</version>

      </dependency>

      <dependency>

        <groupId>com.fasterxml.jackson.module</groupId>

        <artifactId>jackson-module-jaxb-annotations</artifactId>

        <version>2.1.0</version>

      </dependency>





[b]另一种方法:[/b], [color=red]貌似偶尔出问题, 还没找原因[/color]


package cn.com.voge.utils;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.FileCopyUtils;

public class UTF8StringHttpMessageConverter extends
		AbstractHttpMessageConverter<String> {

	public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
	private final List<Charset> availableCharsets;

	public UTF8StringHttpMessageConverter() {
		this(DEFAULT_CHARSET);
	}

	public UTF8StringHttpMessageConverter(Charset defaultCharset) {
		super(new MediaType("text", "plain", defaultCharset), MediaType.ALL);
		this.availableCharsets = new ArrayList<Charset>(Charset
				.availableCharsets().values());
	}

	@Override
	protected boolean supports(Class<?> clazz) {
		return String.class.equals(clazz);
	}

	@Override
	protected String readInternal(Class<? extends String> clazz,
			HttpInputMessage inputMessage) throws IOException,
			HttpMessageNotReadableException {
		MediaType contentType = inputMessage.getHeaders().getContentType();
		Charset charset = contentType.getCharSet() != null ? contentType
				.getCharSet() : DEFAULT_CHARSET;
		return FileCopyUtils.copyToString(new InputStreamReader(inputMessage
				.getBody(), charset));
	}

	@Override
	protected void writeInternal(String t, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {
		MediaType contentType = outputMessage.getHeaders().getContentType();
		Charset charset = contentType.getCharSet() != null ? contentType
				.getCharSet() : DEFAULT_CHARSET;
		FileCopyUtils.copy(t, new OutputStreamWriter(outputMessage.getBody(),
				charset));
	}

	protected List<Charset> getAcceptedCharsets() {
		return this.availableCharsets;
	}

	@Override
	protected Long getContentLength(String s, MediaType contentType) {
		if (contentType != null && contentType.getCharSet() != null) {
			Charset charset = contentType.getCharSet();
			try {
				return (long) s.getBytes(charset.name()).length;
			} catch (UnsupportedEncodingException ex) {
				throw new InternalError(ex.getMessage());
			}
		} else {
			return null;
		}
	}
}


<mvc:annotation-driven>   
	    <mvc:message-converters register-defaults="true">   
	        <bean class="cn.com.voge.utils.UTF8StringHttpMessageConverter"/>   
	    </mvc:message-converters>   
	</mvc:annotation-driven>




[b][color=blue]2.springmvc 3.1解决中文乱码的方法:[/color][/b]


[b]  第一步:在配置文件中加入以下代码: [/b]


<mvc:annotation-driven>

    <mvc:message-converters register-defaults="true">

      <bean class="com.util.spring.UTF8StringHttpMessageConverter"/>

    </mvc:message-converters>

  </mvc:annotation-driven>


[b] 第二步:自定义一个编码转换类:[/b]


public class UTF8StringHttpMessageConverter extends 
        AbstractHttpMessageConverter<String> { 

      public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); 
      private final List<Charset> availableCharsets; 

      public UTF8StringHttpMessageConverter() { 
          this(DEFAULT_CHARSET); 
      } 

      public UTF8StringHttpMessageConverter(Charset defaultCharset) { 
          super(new MediaType("text", "plain", defaultCharset), MediaType.ALL); 
          this.availableCharsets = new ArrayList<Charset>(Charset .availableCharsets().values()); 
      } 

      @Override 
      protected boolean supports(Class<?> clazz) { 
          return String.class.equals(clazz); 
      } 

      @Override 
      protected String readInternal(Class<? extends String> clazz, 
              HttpInputMessage inputMessage) throws IOException, 
              HttpMessageNotReadableException { 
          MediaType contentType = inputMessage.getHeaders().getContentType(); 
          Charset charset = contentType.getCharSet() != null ? contentType.getCharSet() : DEFAULT_CHARSET; 
          return FileCopyUtils.copyToString(new InputStreamReader(inputMessage .getBody(), charset)); 
      } 

      @Override 
      protected void writeInternal(String t, HttpOutputMessage outputMessage) 
              throws IOException, HttpMessageNotWritableException { 
          MediaType contentType = outputMessage.getHeaders().getContentType(); 
          Charset charset = contentType.getCharSet() != null ? contentType .getCharSet() : DEFAULT_CHARSET; 
          FileCopyUtils.copy(t, new OutputStreamWriter(outputMessage.getBody(),  charset)); 
      } 

      protected List<Charset> getAcceptedCharsets() { 
          return this.availableCharsets; 
      } 

      @Override 
      protected Long getContentLength(String s, MediaType contentType) { 
          if (contentType != null && contentType.getCharSet() != null) { 
              Charset charset = contentType.getCharSet(); 
              try { 
                  return (long) s.getBytes(charset.name()).length; 
              } catch (UnsupportedEncodingException ex) {                 
                  throw new InternalError(ex.getMessage()); 
              } 
          } else { 
              return null; 
          } 
      } 
  }


[b] 第三步:加入需要的jackson包:[/b]


<dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>1.8.8</version>
      </dependency>
      <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.8.8</version>
      </dependency>