利用Jackson解决Json乱码问题

  1. 导入Jackson依赖:
<dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.10.0version>
        dependency>
  1. 在springmvc-servlet.xml中配置如下:
  <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>
  1. 扩展: 也可以不使用xml配置的方式(不推荐使用)
@Controller
public class UserController {
     

    @RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
//    @RequestMapping("/j1")
    @ResponseBody   //只要有这个注解,它就不会走视图解析器;会直接返回一个字符串
    public String json1() throws JsonProcessingException {
     
        //Jackson ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        //创建一个对象
        User user = new User("海绵宝宝",20,"男");
        System.out.println(user);
        return mapper.writeValueAsString(user);
    }
}

你可能感兴趣的:(资源配置,工具类,json,java,springmvc)