代码改变世界

java对象转json对象

2018-09-04 12:00  不痒不痛  阅读(406)  评论(0编辑  收藏  举报

org.java类

public class orgs {

    private String id;
    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

  user.java类

public class users {

    private String id;
    private String name;
    private String password;
    private String address;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    
}

  测试类

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class Test {

    /**
     * 
     * @param args
     */
    public static void main(String[] args) {
        users users=new users();
        users.setId("1111");
        users.setName("张三");
        users.setPassword("888888");
        users.setAddress("xxx省");
        
        users u1=new users();
        u1.setId("2222");
        u1.setName("李四");
        u1.setPassword("888888");
        u1.setAddress("xxx省");
        
        orgs orgs=new orgs();
        orgs.setId("1111");
        orgs.setName("xxx省xxx单位");
        
        JSONObject obj=new JSONObject();
        JSONArray userArr=new JSONArray();
        JSONArray orgArr=new JSONArray();
        
        JSONObject json = JSONObject.fromObject(users);
        JSONObject json1 = JSONObject.fromObject(u1);
        JSONObject orgJson = JSONObject.fromObject(orgs);
        userArr.add(json.toString());
        userArr.add(json1.toString());
        orgArr.add(orgJson.toString());
       
        obj.put("users", userArr.toString());
        obj.put("orgs", orgArr.toString());
        System.out.println(obj.toString());
    }

}

  运行结果

{
    "users": [
        {
            "address": "xxx省",
            "id": "1111",
            "name": "张三",
            "password": "888888"
        },
        {
            "address": "xxx省",
            "id": "2222",
            "name": "李四",
            "password": "888888"
        }
    ],
    "orgs": [
        {
            "id": "1111",
            "name": "xxx省xxx单位"
        }
    ]
}