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",jsonObject.toString()); try {
JSONObject object = new JSONObject(jsonObject.toString());
Log.e("MainActivity",object.toString()); } catch (JSONException e) {
e.printStackTrace();
}
输入结果
11-13 14:14:13.846 15433-15433/com.example.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 15433-15433/com.example.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'
HashMap<String,String>map = new HashMap<>();
map.put("a","1");
map.put("b","2");
map.put("c","3"); String json = JSON.toJSONString(map);//map转String
JSONObject jsonObject = JSON.parseObject(json);//String转json //json转map
Map<String, String> jsonMap = JSONObject.toJavaObject(jsonObject, Map.class);
//String转map
Map<String, String> jsonMap1 = JSONObject.parseObject(json, Map.class);