JSON语句解析代码

来源:互联网 发布:印刷体汉字识别数据集 编辑:程序博客网 时间:2024/06/04 23:22
  1. 注:首先导入org.json下面的包  
  2.    
  3. package com.sun;  
  4.   
  5. import org.json.JSONArray;  
  6. import org.json.JSONException;  
  7. import org.json.JSONObject;  
  8.   
  9. public class Test {  
  10.   
  11.     public static void main(String args[]) throws JSONException {  
  12.         String jsonContent = "{'hello':world,'abc':'xyz'}";  
  13.         JSONObject jsonObject = new JSONObject(jsonContent);  
  14.         String str1 = jsonObject.getString("hello");  
  15.         String str2 = jsonObject.getString("abc");  
  16.         System.out.println(str1);  
  17.         System.out.println(str2);  
  18.   
  19.         System.out.println("------------------");  
  20.         jsonContent = "[{'hello':333,'abc':'false','xyz':{'a':1,'b':'ab'}},{'hello':555,'abc':'true','xyz':{'a':2,'b':'ba'}}]";  
  21.         JSONArray jsonArray = new JSONArray(jsonContent);  
  22.         for(int i=0;i<jsonArray.length();i++){  
  23.             JSONObject jsonobject2=jsonArray.getJSONObject(i);  
  24.             int value1=jsonobject2.getInt("hello");  
  25.             boolean value2=jsonobject2.getBoolean("abc");  
  26. //          String value3=jsonobject2.getString("xyz");  
  27.             JSONObject jsonobject3=jsonobject2.getJSONObject("xyz");  
  28.             int value4=jsonobject3.getInt("a");  
  29.             String value5=jsonobject3.getString("b");  
  30.             System.out.println(value1);  
  31.             System.out.println(value2);  
  32.             System.out.println(value4);  
  33.             System.out.println(value5);           
  34.         }  
  35.           
  36.     }  
  37. }  
  38. 输出结果  
  39. world  
  40. xyz  
  41. ------------------  
  42. 333  
  43. false  
  44. 1  
  45. ab  
  46. 555  
  47. true  
  48. 2  
  49. ba 
0 0
原创粉丝点击