- 如果我们需要实现一个配置管理的功能,那么为每个配置项目增加一个字段既复杂也不利于扩展,所以我们通常使用一个字符串来保存配置项目信息,这里介绍如何使用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}
- 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;