如果我們需要實現一個配置管理的功能,那麼爲每個配置項目增加一個字段既複雜也不利於擴展,所以我們通常使用一個字符串來保存配置項目信息,這裏介紹如何使用json的字符串解析來達到剛纔說的目的。引入Json需要的類庫:
import org.json.JSONException;
import org.json.JSONObject;
生成一個json對象(可以添加不同類型的數據):
JSONObject jsonObject = new JSONObject();
jsonObject.put("a", 1);
jsonObject.put("b", 1.1);
jsonObject.put("c", 1L);
jsonObject.put("d", "test");
jsonObject.put("e", true);
System.out.println(jsonObject);
//{"d":"test","e":true,"b":1.1,"c":1,"a":1}
解析一個json對象(可以解析不同類型的數據):
jsonObject = getJSONObject("{d:test,e:true,b:1.1,c:1,a:1}");
System.out.println(jsonObject);
//{"d":"test","e":true,"b":1.1,"c":1,"a":1}
System.out.println(jsonObject.getInt("a"));
System.out.println(jsonObject.getDouble("b"));
System.out.println(jsonObject.getLong("c"));
System.out.println(jsonObject.getString("d"));
System.out.println(jsonObject.getBoolean("e"));
jsonObject = getJSONObject("{d:test,e:true,b:1.1,c:1,a:1}");
System.out.println(jsonObject);
//{"d":"test","e":true,"b":1.1,"c":1,"a":1}
System.out.println(jsonObject.getInt("a"));
System.out.println(jsonObject.getDouble("b"));
System.out.println(jsonObject.getLong("c"));
System.out.println(jsonObject.getString("d"));
System.out.println(jsonObject.getBoolean("e"));
getJSONObject(String str)
public static JSONObject getJSONObject(String str) {
if (str == null || str.trim().length() == 0)
return null;
JSONObject jsonObject = null;
try { jsonObject = new JSONObject(str); }
catch (JSONException e) {
e.printStackTrace(System.err); }
return jsonObject;