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对象的主要内容,如果未能解决你的问题,请参考以下文章