集合对象转json数组

我们来看下需求,用集合转换成json数组

[{
	username: ”test01”,
	mobile: ”15258815948”
}, {
	username: ”test02”,
	mobile: ”15258815948”
}]

  上代码:

public class Mobiles implements Serializable {
    private String userName;
    private String mobile;
    public Mobiles(){}

    public Mobiles(String userName, String mobile) {
        this.userName = userName;
        this.mobile = mobile;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }


    @Override
    public String toString() {
        return "Mobiles{" +
                "userName='" + userName + '\'' +
                ", mobile='" + mobile + '\'' +
                '}';
    }
}

   

public class TestDemo {
    public static void main(String[] args) {
        List<Mobiles> list = new ArrayList<>();
        list.add(new Mobiles("张三", "1234"));
        list.add(new Mobiles("王五", "46565"));
        list.add(new Mobiles("赵四", "4343"));
        JSONArray array = JSONArray.parseArray(JSON.toJSONString(list));
        System.out.println(array);
       }
  }

打印结果:

[{"mobile":"1234","userName":"张三"},{"mobile":"46565","userName":"王五"},{"mobile":"4343","userName":"赵四"}]

 

 

 

 

 

 

 

 

 

 

 

 

 

 

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读