1SpringBoot bean,list,map Json返回

Posted xidianzxm

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1SpringBoot 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

以上是关于1SpringBoot bean,list,map Json返回的主要内容,如果未能解决你的问题,请参考以下文章

[转]解析json:与array,list,map,bean,xml相互转化

1Springboot之事务&aop的核心功能源码分析

fastjson怎么将bean转成map

IOC容器-Bean管理XML方式集合的注入

使用Bean其实优于Map

jsp怎么引用map类