1、SpringBoot bean,list,map Json返回

1、Bean

public class User {
    private int id;
    private String username;
    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}
@RestController
@RequestMapping("user")   
public class ReturnJsoncontroller {

    @RequestMapping("getUser")
    public User getUser(){
        User user = new User();
        user.setId(1);
        user.setUsername("zhanghaoliang");
        user.setPassword("1231");
        return user;
    }
}

http://localhost:8080/user/getUser

2、List

@RestController
@RequestMapping("user")
public class ReturnJsoncontroller {
    
    @RequestMapping("getUserList")
    public List<User> getUserList(){
        User user1  = new User();
        user1.setId(1);
        user1.setUsername("zhanghaoliang");
        user1.setPassword("123");
        User user2 = new User();
        user2.setId(2);
        user2.setUsername("chensi");
        user2.setPassword("456");
        User user3 = new User();
        user3.setId(3);
        user3.setUsername("doudou");
        user3.setPassword("789");
        List<User> list = new ArrayList<>();
        list.add(user1);
        list.add(user2);
        list.add(user3);
        return list;
    }
}

http://localhost:8080/user/getUserList

3、Map

@RestController
@RequestMapping("user")
public class ReturnJsoncontroller {

    @RequestMapping("getUserMap")
    public Map<String,User> getUserMap(){
        User user1  = new User();
        user1.setId(1);
        user1.setUsername("zhanghaoliang");
        user1.setPassword("123");
        User user2 = new User();
        user2.setId(2);
        user2.setUsername("chensi");
        user2.setPassword("456");
        User user3 = new User();
        user3.setId(3);
        user3.setUsername("doudou");
        user3.setPassword("789");
        Map<String,User> map = new HashMap<>();
        map.put("user1",user1);
        map.put("user2",user2);
        map.put("user3",user3);
        return map;
    }
}

http://localhost:8080/user/getUserMap

转发https://www.cnblogs.com/zhanghaoliang/p/7389336.html

posted @ 2019-04-29 19:46  xidianzxm  阅读(1921)  评论(0编辑  收藏  举报