JSONObject

  1. 如果我们需要实现一个配置管理的功能,那么为每个配置项目增加一个字段既复杂也不利于扩展,所以我们通常使用一个字符串来保存配置项目信息,这里介绍如何使用json的字符串解析来达到刚才说的目的。引入Json需要的类库:    
  2. import org.json.JSONException;    
  3. import org.json.JSONObject;    
  4.   
  5. 生成一个json对象(可以添加不同类型的数据):    
  6. JSONObject jsonObject = new JSONObject();   jsonObject.put("a"1);     
  7.  jsonObject.put("b"1.1);    
  8.   jsonObject.put("c", 1L);    
  9.   jsonObject.put("d""test");    
  10.   jsonObject.put("e"true);     
  11.  System.out.println(jsonObject);    
  12.      
  13. //{"d":"test","e":true,"b":1.1,"c":1,"a":1}     
  14.   
  15. JSONObject jsonObject = new JSONObject();   
  16. jsonObject.put("a"1);   
  17. jsonObject.put("b"1.1);   
  18. jsonObject.put("c", 1L);   
  19. jsonObject.put("d""test");   
  20. jsonObject.put("e"true);   
  21. System.out.println(jsonObject);   
  22. //{"d":"test","e":true,"b":1.1,"c":1,"a":1}   
  23.   
  24. 解析一个json对象(可以解析不同类型的数据):    
  25. jsonObject = getJSONObject("{d:test,e:true,b:1.1,c:1,a:1}");     
  26.  System.out.println(jsonObject);      
  27.   
  28. //{"d":"test","e":true,"b":1.1,"c":1,"a":1}     
  29.  System.out.println(jsonObject.getInt("a"));     
  30.  System.out.println(jsonObject.getDouble("b"));     
  31.  System.out.println(jsonObject.getLong("c"));     
  32.  System.out.println(jsonObject.getString("d"));     
  33.  System.out.println(jsonObject.getBoolean("e"));    
  34.  jsonObject = getJSONObject("{d:test,e:true,b:1.1,c:1,a:1}");   
  35.  System.out.println(jsonObject);   
  36.  //{"d":"test","e":true,"b":1.1,"c":1,"a":1}   
  37. System.out.println(jsonObject.getInt("a"));   
  38. System.out.println(jsonObject.getDouble("b"));   
  39. System.out.println(jsonObject.getLong("c"));   
  40. System.out.println(jsonObject.getString("d"));   
  41. System.out.println(jsonObject.getBoolean("e"));   
  42. getJSONObject(String str)   
  43.   
  44. public static JSONObject getJSONObject(String str) {      
  45.   if (str == null || str.trim().length() == 0)       
  46.    return null;       
  47.  JSONObject jsonObject = null;        
  48. try {       jsonObject = new JSONObject(str);     }    
  49. catch (JSONException e) {       
  50.    e.printStackTrace(System.err);     }     
  51.    return jsonObject;     
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值