java调用接口时候,经常需要对json字符串进行操作,下面这个例子就是将json字符串转成java的List/Map
package com.test.jsonToMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
* 将json字符串 转成 List/Map
*/
public class JsonToMap {
public static void main(String[] args) {
// JSONArray
String jsonArrayData = "[{\"a1\":\"12\",\"b1\":\"112\"},{\"a2\":\"12\",\"b2\":\"112\"}]";
JSONArray jsonArray = JSONArray.fromObject(jsonArrayData);
List<Map<String, Object>> mapListJson = (List) jsonArray;
for (int i = 0; i < mapListJson.size(); i++) {
Map<String, Object> obj = mapListJson.get(i);
for (Entry<String, Object> entry : obj.entrySet()) {
String strkey1 = entry.getKey();
Object strval1 = entry.getValue();
System.out
.println("key:" + strkey1 + " --> value:" + strval1);
}
}
System.out.println("=======");
// JSONObject
String jsonObjectData = "{\"data1\":{\"a1\":\"12\",\"b1\":\"112\"},\"data2\":{\"a2\":\"12\",\"b2\":\"112\"}}";
JSONObject jsonObject = JSONObject.fromObject(jsonObjectData);
Map<String, Object> mapJson = JSONObject.fromObject(jsonObject);
for (Entry<String, Object> entry : mapJson.entrySet()) {
Object strval1 = entry.getValue();
JSONObject jsonObjectStrval1 = JSONObject.fromObject(strval1);
Map<String, Object> mapJsonObjectStrval1 = JSONObject
.fromObject(jsonObjectStrval1);
for (Entry<String, Object> entry1 : mapJsonObjectStrval1.entrySet()) {
System.out.println("key:" + entry1.getKey() + " --> value:"
+ entry1.getValue());
}
}
}
}
json-lib-2.3-jdk15.jar