JAva解析とjsonオブジェクトの接合

2804 ワード

/**
 * @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));   
  }
 }
}