1、如果我們需要實現一個組態管理的功能,那麼為每個設定項目增加一個欄位既複雜也不利於擴充,所以我們通常使用一個字串來儲存設定項目資訊,這裡介紹如何使用json的字串解析來達到剛才說的目的。引入Json需要的類庫:
import org.json.JSONException;
import org.json.JSONObject;
2、產生一個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}
3、解析一個json對象(可以解析不同類型的資料),getJSONObject(String str):
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"));
4、
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;
}
包:http://www.json.org/java/index.html