1.如果我們需要實(shí)現(xiàn)一個(gè)配置管理的功能,那么為每個(gè)配置項(xiàng)目增加一個(gè)字段既復(fù)雜也不利于擴(kuò)展,所以我們通常使用一個(gè)字符串來(lái)保存配置項(xiàng)目信息,這里介紹如何使用json的字符串解析來(lái)達(dá)到剛才說(shuō)的目的。引入Json需要的類庫(kù):


1
import org.json.JSNException; 02.import org.json.JSONObject;
2.生成一個(gè)json對(duì)象(可以添加不同類型的數(shù)據(jù)):
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.解析一個(gè)json對(duì)象(可以解析不同類型的數(shù)據(jù)):
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
}
這樣我們不僅可以處理多種數(shù)據(jù)類型,還可以隨時(shí)添加配置相,這種方式相當(dāng)靈活。
posted on 2010-01-20 17:59
Werther 閱讀(3227)
評(píng)論(0) 編輯 收藏 所屬分類:
10.Java