import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public static void main(String[] args) throws JSONException { String sJson = "[{'gwcxxid':'1','spsl':'2'},{'gwcxxid':'1','spsl':'2'},{'gwcxxid':'3','spsl':'4'}]"; JSONArray jsonArray = new JSONArray(sJson); int iSize = jsonArray.length(); System.out.println("Size:" + iSize); for (int i = 0; i < iSize; i++) { JSONObject jsonObj = jsonArray.getJSONObject(i); System.out.println("[" + i + "]gwcxxid=" + jsonObj.get("gwcxxid")); System.out.println("[" + i + "]spsl=" + jsonObj.get("spsl")); System.out.println(); } }
上面的是将json数组循环遍历输出的方法
下面的是将对象封装进json数组并返回,具体步骤看下图
/** * @author: helloworlda * @time:2012-1-18 * @descript:java拼接和解析json对象 * @result:get没测试出来,不知道效率怎么样。 */ package json; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.sf.json.JSONArray; import net.sf.json.JSONObject; /** * */ public class TestJson { public static void main(String[] args) { System.out.println("---------------------java拼接json对象----------------------"); TestJson ss=new TestJson(); ss.viewMagazine(); System.out.println("---------------------java解析json对象----------------------"); strJsonObj(); } /** * 拼json对象 */ public String viewMagazine(){ Person person=new Person(); person.setBirth("1989-22-11"); person.setGrade("07java"); person.setName("happ"); person.setSex("boy"); //推荐的杂志的结果集 Person person1=new Person(); person1.setBirth("1989-22-11"); person1.setGrade("07java"); person1.setName("helloworlda"); person1.setSex("girl"); List<Person> list=new ArrayList<Person>(); list.add(person); list.add(person1); JSONObject s=new JSONObject(); JSONArray ss=JSONArray.fromObject(list);//构建json数组 //往json对象中加值 s.put("person", person);//添加对象 s.put("personlist", list);//添加数组,list和ss都可以 //s.put("personss", ss);//添加数组,list和ss都可以 s.put("comCount", 3); System.out.println(s); return null; } /** * java解析json对象,解析出对象和字符串及数组并遍历出相应的值 */ private static void strJsonObj(){ String json = "{'name': 'helloworlda','array':[{'a':'111','b':'222','c':'333'},{'a':'999'}],'address':'111','people':{'name':'happ','sex':'girl'}}"; JSONObject jsonobj=JSONObject.fromObject(json);//将字符串转化成json对象 String name=jsonobj.getString("name");//获取字符串。 JSONArray array=jsonobj.getJSONArray("array");//获取数组 JSONObject obj=jsonobj.getJSONObject("people");//获取对象 System.out.println("===============strJsonObj=================="); System.out.println("jsonobj : "+jsonobj); System.out.println("array : "+array); System.out.println("obj : "+obj.getString("name")); //遍历json对象 Iterator<?> objkey=obj.keys(); while (objkey.hasNext()) {// 遍历JSONObject String aa2 = (String) objkey.next().toString(); String bb2 = obj.getString(aa2); System.out.println(aa2+":"+bb2); } //遍历数组 for (int i = 0; i < array.size(); i++) { System.out.println("item "+ i + " :" + array.getString(i)); } }
}
刘斌找到的方法
http://blog.csdn.net/Xurns/article/details/51593156