Json

Json_第1张图片

package com.test.model;
import java.util.*;
import com.test.entity.Student;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class TestJson {
   public static void main(String[] args) {
   //List集合转换成json代码
   List list = new ArrayList();
   list.add( "first" ); list.add( "second" );
   JSONArray jsonArray2 = JSONArray.fromObject( list );
   System.out.println(jsonArray2);
   
    //数组转换成json代码
    boolean[] boolArray = new boolean[] { true, false, true };
    JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
    System.out.println(jsonArray1);
   
    //beans转换成json代码
    List  StudentsList = new ArrayList<Student>();
    Student s1 = new Student();
    s1.setId(1); s1.setName("张三");s1.setAge("18");s1.setGender("男");
    Student s2 = new Student();
    s2.setId(2);s2.setName("李四");s2.setAge("19"); s2.setGender("男");
    StudentsList.add(s1); StudentsList.add(s2);
    JSONArray jsons=JSONArray.fromObject(StudentsList);   
    Iterator it=jsons.listIterator();
         while(it.hasNext()) { 
            JSONObject obj=(JSONObject)it.next();
            Student s=(Student)JSONObject.toBean(obj,Student.class); 
            System.out.println(s.getName());
         } 
     
     //Map集合转换成json代码   
     Map map = new HashMap();
     map.put("name", "json");
     map.put("bool", Boolean.TRUE);
     map.put("int", new Integer(1));
     map.put("arr", new String[] { "a", "b" });
     map.put("func", "function(i){ return this.arr[i]; }");
     JSONObject json = JSONObject.fromObject(map);
     System.out.println(json);    
         
      //String转JSON 
        String listStr = "['apple','orange']";        
        JSONArray json1 = JSONArray.fromObject(listStr);
           //必须用JSONArray来转,用JSONObject会出现以下错误信息:  A JSONObject text must begin with '{' at character 1 of ['apple','orange']  
            String mapStr = "{'age':30,'name':'Michael','baby':['Lucy','Lily']}";        
        JSONObject json2 = JSONObject.fromObject(mapStr);                             
        System.out.println(json1);
        System.out.println(json2);
        
    //JSON转List、Map 
 //JSON转List  
      String str = "['apple','orange']";  
      JSONArray jsonss = JSONArray.fromObject(str);  
      Collection<String> lists = JSONArray.toCollection(jsonss);  
      for (String s : lists) {  
                   System.out.println(s); 
          }
 
   //JOSN转Map  
       String mapStr1 = "{'age':30,'name':'Michael','baby':['Lucy','Lily']}";  
       JSONObject json3 = JSONObject.fromObject(mapStr1);  
       Map<String, Object> maps = (Map) JSONObject.toBean(json3, Map.class);  
       for (Map.Entry<String, Object> entry : maps.entrySet()) {  
                System.out.println(entry.getKey() + " " + entry.getValue());  
        }              
   }
 }
 相关链接:http://uule.iteye.com/blog/831894


你可能感兴趣的:(Json)