十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
例如:
创新互联长期为成百上千客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为宣威企业提供专业的做网站、成都网站制作,宣威网站改版等技术服务。拥有十余年丰富建站经验和众多成功案例,为您定制开发。
Student st1 = new Student(1, "dg", 18, new Date());
Student st2 = new Student(2, "dg", 18, new Date());
Student st3 = new Student(3, "dg", 18, new Date());
Student st4 = new Student(4, "dg", 18, new Date());
Student st5 = new Student(5, "dg", 18, new Date());
List li = new ArrayList();
JSONObject JO1 = new JSONObject(st1);
JSONObject JO2 = new JSONObject(st2);
JSONObject JO3 = new JSONObject(st3);
JSONObject JO4 = new JSONObject(st4);
JSONObject JO5 = new JSONObject(st5);
li.add(JO1);
li.add(JO2);
li.add(JO3);
li.add(JO4);
li.add(JO5);
JSONArray Ja = new JSONArray(li);
Map ma = new HashMap();
ma.put("Result", "OK");
ma.put("Records", Ja);
JSONObject js = new JSONObject(ma);
out.print(js);
返回结果:
{"Result":"OK","Records":[{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":1},{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":2},{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":3},{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":4},{"recordDate":"Fri Dec 16 17:54:39 CST 2011","name":"dg","age":18,"personId":5}]}
将json字符串转换为java对象
同样先将json字符串转换为json对象,再将json对象转换为java对象,如下所示。
JSONObject obj = new JSONObject().fromObject(jsonStr);//将json字符串转换为json对象
将json对象转换为java对象
Person jb = (Person)JSONObject.toBean(obj,Person.class);//将建json对象转换为Person对象
3.将java对象转换为json字符串
先将java对象转换为json对象,在将json对象转换为json字符串
JSONObject json = JSONObject.fromObject(obj);//将java对象转换为json对象
String str = json.toString();//将json对象转换为字符串
处理基本的java对象使用JSONObject类,用法大体如下:
public void testMap(){
MapString,Object map = new HashMapString,Object();
map.put("name", "qiu");
map.put("password", "123");
map.put("address", "china");
User user = new User();
user.setUserName("qiuqiu");
user.setPassword("123456");
user.getTels().add("1234444556677");
user.getTels().add("6893493458585");
map.put("user", user);
JSONObject json = new JSONObject(map);
System.out.println(json.toString());
}
官方的JSONArray并不支持javabean的直接转换,比如ListUser是不能转换的,必须要把它转换成ListMap这样的格式,才能转换。