
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對象(可以解析不同類型的數(shù)據(jù)): 
2

3

4

5

6

7

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)
2

3

4

5

6

7

8

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ù)類型,還可以隨時添加配置相,這種方式相當靈活。

2

3

4

5

6

7

8

9

10

11
