随笔-199  评论-203  文章-11  trackbacks-0
1.如果我们需要实现一个配置管理的功能,那么为每个配置项目增加一个字段既复杂也不利于扩展,所以我们通常使用一个字符串来保存配置项目信息,这里介绍如何使用json的字符串解析来达到刚才说的目的。引入Json需要的类库:
2.生成一个json对象(可以添加不同类型的数据):
1JSONObject jsonObject = new JSONObject();   jsonObject.put("a"1);   
2jsonObject.put("b"1.1);   
3jsonObject.put("c"1L);   
4jsonObject.put("d""test");   
5jsonObject.put("e"true);   
6System.out.println(jsonObject);   
7//{"d":"test","e":true,"b":1.1,"c":1,"a":1} 
3.解析一个json对象(可以解析不同类型的数据):
1jsonObject = getJSONObject("{d:test,e:true,b:1.1,c:1,a:1}");   
2System.out.println(jsonObject);   
3//{"d":"test","e":true,"b":1.1,"c":1,"a":1}   
4System.out.println(jsonObject.getInt("a"));   
5System.out.println(jsonObject.getDouble("b"));   
6System.out.println(jsonObject.getLong("c"));   
7System.out.println(jsonObject.getString("d"));
8System.out.println(jsonObject.getBoolean("e"));  
getJSONObject(String str)
 1public static JSONObject getJSONObject(String str) {   
 2 if (str == null || str.trim().length() == 0)   
 3 return null;  
 4 JSONObject jsonObject = null;  
 5 try 
 6 jsonObject = new JSONObject(str); 
 7 }
 catch (JSONException e) {   
 8 e.printStackTrace(System.err);  
 9 }
   
10  return jsonObject;   
11 }
  
这样我们不仅可以处理多种数据类型,还可以随时添加配置相,这种方式相当灵活。
posted on 2010-01-20 17:59 Werther 阅读(3211) 评论(0)  编辑  收藏 所属分类: 10.Java

只有注册用户登录后才能发表评论。


网站导航: