java对象转json对象

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java对象转json对象相关的知识,希望对你有一定的参考价值。

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单位"
        }
    ]
}

  

以上是关于java对象转json对象的主要内容,如果未能解决你的问题,请参考以下文章

java中把json怎么转换成数组?

JSON字符串转实体对象

json转java对象

如何将json字符串转成带有对象引用的java对象

一个java对象内包含一个对象集合 用json-lib框架怎么转换成JSON数据格式

怎样在java代码里获取一个json对象,然后对其进行排序,排好了之后,再返回给json?