JSON与对象的转换-JSONObject.fromObject
使用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);
输出结果为:
相关推荐
WebVincent 2020-07-21
fengchao000 2020-07-04
baijinswpu 2020-06-28
88483063 2020-06-28
fengchao000 2020-06-16
somebodyoneday 2020-06-15
wujiajax 2020-06-14
somebodyoneday 2020-05-16
xx0cw 2020-05-16
newthon 2020-05-14
sailxu00 2020-04-27
fengchao000 2020-04-20
88483063 2020-01-29
83163452 2020-01-28
baijinswpu 2020-01-25
baijinswpu 2020-01-18