使用JSONObject.fromObject把字符串轉化為json
例如:有一個json格式的字符串,然后通過JSONObject.fromObject把字符串轉化為json,然后獲取值。代碼如下:
String d="{\"username\":\"zhangsan\",\"password\":\"zhangsan\"}"; JSONObject json4=JSONObject.fromObject(d); System.out.println(json4); System.out.println(json4.optString("username"));
輸出的結果為:
注意:還有一種情況也是可以轉化的,如下代碼的字符串e所示,這個字符串並不是一個json格式的字符串,但也可以轉化成json
String d="{\"username\":\"zhangsan\",\"password\":\"zhangsan\"}"; JSONObject json4=JSONObject.fromObject(d); String e="{\"username\"=\"lisi\",\"password\"=\"lisi\"}"; JSONObject json5=JSONObject.fromObject(e); System.out.println(json4); System.out.println(json4.optString("username")); System.out.println(json5);
輸出結果為: