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 閱讀(3228)
評論(0) 編輯 收藏 所屬分類:
10.Java