1.如果我们需要实现一个配置管理的功能,那么为每个配置项目增加一个字段既复杂也不利于扩展,所以我们通常使用一个字符串来保存配置项目信息,这里介绍如何使用json的字符串解析来达到刚才说的目的。引入Json需要的类库:


1
import org.json.JSNException; 02.import org.json.JSONObject;
2.生成一个json对象(可以添加不同类型的数据):
1
JSONObject jsonObject = new JSONObject(); jsonObject.put("a", 1);
2
jsonObject.put("b", 1.1);
3
jsonObject.put("c", 1L);
4
jsonObject.put("d", "test");
5
jsonObject.put("e", true);
6
System.out.println(jsonObject);
7
//{"d":"test","e":true,"b":1.1,"c":1,"a":1}
3.解析一个json对象(可以解析不同类型的数据):
1
jsonObject = getJSONObject("{d:test,e:true,b:1.1,c:1,a:1}");
2
System.out.println(jsonObject);
3
//{"d":"test","e":true,"b":1.1,"c":1,"a":1}
4
System.out.println(jsonObject.getInt("a"));
5
System.out.println(jsonObject.getDouble("b"));
6
System.out.println(jsonObject.getLong("c"));
7
System.out.println(jsonObject.getString("d"));
8
System.out.println(jsonObject.getBoolean("e"));
getJSONObject(String str)
1
public 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 阅读(3223)
评论(0) 编辑 收藏 所属分类:
10.Java