spring @RespnoseBody 返回json类型的数据

换spring 4后,以前的json配置总是出问题
后来发现,spring 4必须要用新的配置
在spring配置文件中application.xml配置如下


    
        
            text/html;charset=UTF-8
        
    

而以前spring3 该配置为:


    
        
            
        
    

注意:class已经发生了变化,
spring 4使用的是org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
spring 3使用的是org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter

如果使用的gradle,添加如下依赖

    // https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.7.4'

    // https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.7.4'

    // https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.7.4'

maven配置如下





 com.fasterxml.jackson.core

 jackson-databind

 2.7.4





 com.fasterxml.jackson.core

 jackson-core

 2.7.4





 com.fasterxml.jackson.core

 jackson-annotations

 2.7.4


Controller如下
加上@ResponseBody就可以返回json类型的数据

@Controller
@RequestMapping("index")
public class IindexController {
    @RequestMapping("")
    public String index() {

        return "reglog/login";
    }

    @RequestMapping(value = "sendSMS")
    @ResponseBody
    public Emp send(String phone) {
        Emp emp = new Emp();
        emp.setAge(21);
        emp.setCreateTime(new Date());
        emp.setName("你好");

        String code = SMSMessage.generateCode(6);
        SMSMessage.sendSmsCode(phone, code, "1");
        return emp;
    }
}

参考资料:
http://blog.csdn.net/caiwenfeng_for_23/article/details/43492973
http://www.sojson.com/blog/145.html

你可能感兴趣的:(spring @RespnoseBody 返回json类型的数据)