Spring MVC对象转换成JSON数据后回写

1,相关依赖

  
            org.springframework
            spring-context
            5.2.8.RELEASE
        

        
            org.springframework
            spring-webmvc
            5.2.8.RELEASE
        


        
        
            com.fasterxml.jackson.core
            jackson-core
            2.9.2
        
        
        
            com.fasterxml.jackson.core
            jackson-databind
            2.9.2
        
        
        
            com.fasterxml.jackson.core
            jackson-annotations
            2.9.0
        

2.配置文件spring-config.xml



    

    
    

3.User类

package com.yy.pojo;

public class User {

    private String username;
    private String password;
    //getter和setter方法
}

4.UserController类

package com.yy.controller;

import com.yy.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
/**
 * @RestController  相当于@Controller +  @ResponseBody
 * @ResponseBody 通常用于返回JSON数据 可以标注在类和方法上.
 */
@RestController
public class UserController {
    
    @RequestMapping("/getUser")
    public User getUser(){
        User user = new User("张三","123");
        return user;
    }
    @RequestMapping("/getList")
    public List getList(){
        ArrayList userList = new ArrayList();
        User user1 = new User("张三","123");
        User user2 = new User("张三","123");
        User user3 = new User("张三","123");
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        return userList;
    }
}

你可能感兴趣的:(java,EE企业级应用开发,spring,mvc,json)