1 /** 2 * @author ZWQ 3 * **/ 4 public class JsonTest { 5 public static void main(String[] args) { 6 //*********************************************************************** 7 // json基本测试 8 { 9 //新建一个JSON数组 10 JSONArray jsonArray = new JSONArray(); 11 //新建一个JSON对象 12 JSONObject json1 = new JSONObject(); 13 json1.put("id", "1"); 14 json1.put("name", "张三"); 15 json1.put("password", "123456"); 16 //将JSON对象添加到JSON数组中去 17 jsonArray.add(json1); 18 19 JSONObject json2 = new JSONObject(); 20 json2.put("id", "2"); 21 json2.put("name", "李四"); 22 json2.put("password", "654321"); 23 jsonArray.add(json2); 24 System.out.println("json数组基本测试:" + jsonArray); 25 26 //结果: 27 //[{"id":"1","name":"张三","password":"123456"},{"id":"2","name":"李四","password":"654321"}] 28 } 29 30 //*********************************************************************** 31 //将对象转成JSON字符串 32 { 33 Book book = new Book(); 34 book.setName("Java入门教程"); 35 book.setPrice(52.3); 36 //将Java对象转成JSON对象 37 JSONObject jsonObject = JSONObject.fromObject(book); 38 System.out.println("从Object到JSONObject:" + jsonObject.toString()); 39 40 //结果: 41 //从Object到JSONObject:{"name":"Java入门教程","price":52.3} 42 } 43 44 //*********************************************************************** 45 //将对象集合转成JSON字符串 46 { 47 List<Book> list = new ArrayList<Book>(); 48 Book book1 = new Book(); 49 book1.setName("高等数学I"); 50 book1.setPrice(34.1); 51 Book book2 = new Book(); 52 book2.setName("线性代数"); 53 book2.setPrice(12.7); 54 list.add(book1); 55 list.add(book2); 56 //将List集合转为JSON数组 57 JSONArray jsonArray= JSONArray.fromObject(list); 58 System.out.println("从Object集合到JSONArray:" + jsonArray.toString()); 59 60 //结果: 61 //从Object集合到JSONArray:[{"name":"高等数学I","price":34.1},{"name":"线性代数","price":12.7}] 62 } 63 64 //*********************************************************************** 65 // 将JSON字符串转为Java对象 66 { 67 String jsonString = "{name:'数据结构',price:52.3}"; 68 JSONObject jsonObject = JSONObject.fromObject(jsonString); 69 //将JSON对象转为Java对象 70 Book book = (Book) JSONObject.toBean(jsonObject, Book.class); 71 System.out.println(book.toString()); 72 73 //结果: 74 //数据结构 52.3 75 } 76 77 //*********************************************************************** 78 //将JSON字符串转为Java对象数组 79 { 80 // (2).Bean的数组 81 String jsonsString = "[{name:'数据库基础',price:52.3},{name:'Oracle 11g精华',price:42.3}]"; 82 JSONArray jsonArray = JSONArray.fromObject(jsonsString); 83 //将JSON数组转为Java对象数组 84 Book[] books = (Book[]) JSONArray.toArray(jsonArray, Book.class); 85 for (Book b : books) { 86 System.out.println(b.toString()); 87 } 88 89 //结果: 90 //数据库基础 52.3 91 //Oracle 11g精华 42.3 92 } 93 } 94 } |