JavaBean,List,Map,json格式之间转化方式
public class TestBean { private String id; private String name; private String password; 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 class test { public static void main(String[] args) { List<TestBean> list = new ArrayList<TestBean>(); TestBean ts1 = new TestBean(); ts1.setId("1"); ts1.setName("a"); ts1.setPassword("aaa"); TestBean ts2 = new TestBean(); ts2.setId("2"); ts2.setName("b"); ts2.setPassword("bbb"); TestBean ts3 = new TestBean(); ts3.setId("3"); ts3.setName("c"); ts3.setPassword("ccc"); list.add(0,ts1); list.add(1,ts2); list.add(2,ts3); /*JavaBean2JSONObject & JavaBean2JSONArray */ JSONObject beanObj = JSONObject.fromObject(ts1); JSONArray beanArr = JSONArray.fromObject(ts1); System.out.println(beanObj); System.out.println(beanArr); /*result * {"id":"1","name":"a","password":"aaa"} * [{"id":"1","name":"a","password":"aaa"}] */ /*List2JSONObject & List2JSONArray */ JSONObject obj = JSONObject.fromObject(ts1); JSONArray arr = JSONArray.fromObject(list); System.out.println(obj); System.out.println(arr); /*result: *{"id":"1","name":"a","password":"aaa"} *[{"id":"1","name":"a","password":"aaa"},{"id":"2","name":"b","password":"bbb"},{"id":"3","name":"c","password":"ccc"}] */ /*Map2JSONObject*/ Map<String,Object> listMap = new HashMap(); listMap.put("list",list); JSONArray mapArr = JSONArray.fromObject(listMap); Map<String,Object> beanMap = new HashMap(); beanMap.put("id",ts1); JSONArray beanMapArr = JSONArray.fromObject(beanMap); System.out.println(mapArr); System.out.println(beanMapArr); /*result *[{"list":[{"id":"1","name":"a","password":"aaa"},{"id":"2","name":"b","password":"bbb"},{"id":"3","name":"c","password":"ccc"}]}] *[{"id":{"id":"1","name":"a","password":"aaa"}}] */ } }
参考:http://blog.csdn.net/encienqi/article/details/7840532