8. SpringMVC 返回Json格式

Json解析工具

目前比较流行的有:Jaskson,fastjson 等

  • 导入Jaskson依赖


    com.fasterxml.jackson.core
    jackson-databind
    2.13.1

  • 配置SpringMVC

web.xml




    
    
        springmvc
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:springmvc-servlet.xml
        
        1
    

    
        springmvc
        /
    

    
        index.jsp
    

    
    
        encoding
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            utf-8
        
    
    
        encoding
        /*
    

springmvc-servlet.xml




    
    
    
    
    
    
    
        
            
                
            
            
                
                    
                        
                    
                
            
        
    

    
    
        
        
        
        
    

  • 创建Controller
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hunter.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @RequestMapping(value = "/j1")
    //@ResponseBody // 加了@ResponseBody 就不会走视图解析器,会直接返回一个字符串
    public User json1() throws JsonProcessingException {
        User user = new User("庆", 18, "male");
        return user;
    }
}

@Controller 当前Controller下所有public方法返回结果会走视图解析器
@RestController 当前Controller下所有Public方法返回结果为json字符串
@ResponseBody 指定当前方法返回结果不走视图解析器

你可能感兴趣的:(8. SpringMVC 返回Json格式)