JavaBean到JSon格式的转换功能,依赖JSON的Jar包文件,现有JSON的Jar包文件以及小例子。
User u = new User(); u.setId(1); u.setName("lizhi"); u.setAge(24); u.setHeigh("178cm"); u.setPassword("lizhi@0324"); //Bean User u2 = new User(); u2.setId(2); u2.setName("lizhi2"); u2.setAge(22); u2.setHeigh("1782cm"); u2.setPassword("lizhi@03242"); JSONObject json = JSONObject.fromObject(u); System.out.println(json.toString()); // 结果为:{"age":24,"heigh":"178cm","id":1,"name":"lizhi","password":"lizhi@0324"} // List List<Object> list = new ArrayList<Object>(); list.add(u); list.add(u2); JSONArray jsonList = JSONArray.fromObject(list); System.out.println(jsonList.toString()); // 结果为:[{"age":24,"heigh":"178cm","id":1,"name":"lizhi","password":"lizhi@0324"},{"age":22,"heigh":"1782cm","id":2,"name":"lizhi2","password":"lizhi@03242"}] //Map HashMap<String, Comparable> map = new HashMap<String, Comparable>(); map.put("name", "hzucmj"); map.put("age", 22); JSONObject jsonMap = JSONObject.fromObject(map); System.out.println(jsonMap.toString()); //结果为:{"age":22,"name":"hzucmj"}