JSONObject,String,Map互相转换
JSONObject和String相互转换
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
try {
jsonObject.put("a","1");
jsonObject.put("b","2");
jsonObject.put("c","3");
jsonObject.put("d","4");
for(int i=0;i<10;i++){
JSONObject object = new JSONObject();
object.put("name",i+"");
jsonArray.put(object);
}
jsonObject.put("abcd",jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("MainActivity",String());
try {
JSONObject object = new String());
Log.e("MainActivity",String());
} catch (JSONException e) {
e.printStackTrace();
}
输⼊结果
11-13 14:14:13.846 ample.apple.demo E/MainActivity:
{"a":"1","b":"2","c":"3","d":"4","abcd":[{"name":"0"},{"name":"1"},{"name":"2"},{"name":"3"},{"name":"4"},{"name":"5"},{"name":"6"},{"name":"7"},{"name":"8"},{"name":"9"}]} 11-13 14:14:13.846 ample.apple.demo E/MainActivity: {"a":"1","b":"2","c":"3","d":"4","abcd":[{"name":"0"},{"name":"1"},{"name":"2"},{"name":"3"},{"name":"4"},{"name":"5"},{"name":"6"},{"name":"7"},{"name":"8"},{"name":"9"}]} JSONObject和Map相互转换,这个转换需要⼀个第三⽅的库⽂件,我⽐较喜欢⽤FastJson,具体使⽤请看我的另外⼀篇博客
compile 'com.alibaba:fastjson:1.2.41'
object toHashMap<String,String>map = new HashMap<>();
map.put("a","1");
map.put("b","2");
map.put("c","3");
String json = JSONString(map);//map转String
JSONObject jsonObject = JSON.parseObject(json);//String转json
//json转map
Map<String, String> jsonMap = JavaObject(jsonObject, Map.class);
//String转map
Map<String, String> jsonMap1 = JSONObject.parseObject(json, Map.class);

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。