- 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();
- }
- 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;
- }
- 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));
- }
- }
- }