如何将string转换成json

如题所述

string转json有三种方法

第一种:string直接转json

String json = "{\"2\":\"efg\",\"1\":\"abc\"}"; JSONObject json_test =
JSONObject.fromObject(json); 将string的双引号转义即可,适用于字符串较短的

第二种:将string转为list后转为json

Listlist = new ArrayList(); list.add("username");
list.add("age"); list.add("sex"); JSONArray array = new JSONArray();
array.add(list);

可以使用list的add函数将需要的字符串拼接即可,但是这个只能使用jsonarry

第三种:将string转为map后转为json

Mapmap = new HashMap();

map.put("1", "abc");

map.put("2", "efg");

JSONArray array_test = new JSONArray();

array_test.add(map);

JSONObject jsonObject = JSONObject.fromObject(map);

这里使用map就可以将字符串转化为JSONArray或者JSONObject都可以,但是这里的键不能使用int型

温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网