package com.hanchao.web; import net.sf.json.JSONArray; import net.sf.json.JSONObject; /*********************** * java解析json * @author:han * @version:1.0 * @created:2013-8-28 *********************** */ public class TestJson { public static void main(String[] args) { String json = "{'id':1," + "'username':{'tom':'tom','jerry':'jerry'}," + "'address':[{'us':'usa','cancada':'canada'},{'chi':'china','aus':'aus'}]}"; JSONObject jo = JSONObject.fromObject(json); System.err.println("1--:" + jo.get("id")); JSONObject uObject = jo.getJSONObject("username"); System.out.println("2--username:" + uObject); System.out.println("2--username:" + uObject.get("tom")); JSONArray addressArray = jo.getJSONArray("address"); System.out.println("3--:" + addressArray.getJSONObject(0)); System.out.println("3--:" + addressArray.getJSONObject(0).get("us")); System.out.println("3--:" + addressArray.getJSONObject(1).get("chi")); } }
結果:java
1--:1web
2--username:{"tom":"tom","jerry":"jerry"}json
2--username:tom數組
3--:{"us":"usa","cancada":"canada"}ide
3--:usa對象
3--:chinaget
============對象轉爲JSON對象---------------it
Map<String, Object> map = new HashMap<String, Object>(); map.put("id", 1); map.put("username", "hanchao"); map.put("password", 123L); String toJson = JSONObject.fromObject(map).toString(); System.out.println("toJSON:" + toJson); JSONObject jo1 = JSONObject.fromObject(toJson); System.out.println("id:" + jo1.getInt("id") + ", username:" + jo1.getString("username") + ", password:" + jo1.getString("password")); //2014-04-03-把List集合轉爲JSon數組-------------------------------------------- //方法一: List<User> list = new ArrayList<User>(); User u1 = new User(); u1.setId(1); u1.setUsername("u1"); u1.setPassword("p1"); User u2 = new User(); u2.setId(2); u2.setUsername("u2"); u2.setPassword("p2"); list.add(u1); list.add(u2); String resultJson = JSONArray.fromObject(list).toString(); System.out.println(" ========= : " + resultJson); //方法二: JSONArray array = new JSONArray(); for(User user : list) { JSONObject obj = new JSONObject(); obj.put("username", user.getUsername()); obj.put("id", user.getId()); obj.put("password", user.getPassword()); array.add(obj); } String resultJSON2 = array.toString(); System.out.println(" ========= : " + resultJSON2);