JSONObject,JSON,和JSONArray

来源:互联网 发布:qq飞车大q吧数据 编辑:程序博客网 时间:2024/05/11 22:28
  1. 注:首先导入org.json下面的包  
  2. 直接访问月月鸟博客:
  3.  http://www.cnblogs.com/java-pan/archive/2012/04/07/2436507.html  
  4. package com.sun;  
  5.   
  6. import org.json.JSONArray;  
  7. import org.json.JSONException;  
  8. import org.json.JSONObject;  
  9.   
  10. public class Test {  
  11.   
  12.     public static void main(String args[]) throws JSONException {  
  13.         String jsonContent = "{'hello':world,'abc':'xyz'}";  
  14.         JSONObject jsonObject = new JSONObject(jsonContent);  
  15.         String str1 = jsonObject.getString("hello");  
  16.         String str2 = jsonObject.getString("abc");  
  17.         System.out.println(str1);  
  18.         System.out.println(str2);  
  19.   
  20.         System.out.println("------------------");  
  21.         jsonContent = "[{'hello':333,'abc':'false','xyz':{'a':1,'b':'ab'}},{'hello':555,'abc':'true','xyz':{'a':2,'b':'ba'}}]";  
  22.         JSONArray jsonArray = new JSONArray(jsonContent);  
  23.         for(int i=0;i<jsonArray.length();i++){  
  24.             JSONObject jsonobject2=jsonArray.getJSONObject(i);  
  25.             int value1=jsonobject2.getInt("hello");  
  26.             boolean value2=jsonobject2.getBoolean("abc");  
  27. //          String value3=jsonobject2.getString("xyz");  
  28.             JSONObject jsonobject3=jsonobject2.getJSONObject("xyz");  
  29.             int value4=jsonobject3.getInt("a");  
  30.             String value5=jsonobject3.getString("b");  
  31.             System.out.println(value1);  
  32.             System.out.println(value2);  
  33.             System.out.println(value4);  
  34.             System.out.println(value5);           
  35.         }  
  36.           
  37.     }  
  38. }  
  39. 输出结果  
  40. world  
  41. xyz  
  42. ------------------  
  43. 333  
  44. false  
  45. 1  
  46. ab  
  47. 555  
  48. true  
  49. 2  
  50. ba  
0 0