import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JsonUtil{
public static Map<String, Object> parseJSON2Map(JSONObject json) {
Map<String, Object> map = new HashMap<String, Object>();
for (Object k : json.keySet()) {
Object v = json.get(k);
if (v instanceof JSONArray) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Iterator<JSONObject> it = ((JSONArray) v).iterator();
while (it.hasNext()) {
JSONObject json2 = it.next();
list.add(parseJSON2Map(json2));
}
map.put(k.toString(), list);
} else if (v instanceof JSONObject) {
map.put(k.toString(), parseJSON2Map((JSONObject) v));
} else {
map.put(k.toString(), v);
}
}
return map;
}
public static Map<String, Object> parseJSONstr2Map(String jsonStr) {
JSONObject json = JSONObject.fromObject(jsonStr);
Map<String, Object> map = parseJSON2Map(json);
return map;
}
}
public static void main(String[] args) {
JSONObject json = new JSONObject();
json.put("id","1");
json.put("name","张三");
json.put("pwd","123456");
System.out.println(json);
String json2 = "{\"country\":\"中国\",\"country_code_iso2\":\"CHN\",\"province\":\"北京市\"}";
Map<String, Object> myresult = parseJSONstr2Map("{" +
"\"data\": {" +
"\"studentList\": [{" +
"\"scourse\": {" +
"\"cname\": \"语文,数学,英语\"," +
"\"cscore\": \"93,95,98\"" +
"}," +
"\"sname\": \"张三\"," +
"\"sage\": \"20\"," +
"\"sid\": \"101\"" +
"}," +
"{" +
"\"scourse\": {" +
"\"cname\": \"物理,化学,生物\"," +
"\"cscore\": \"92,93,97\"" +
"}," +
"\"sname\": \"李四\"," +
"\"sage\": \"30\"," +
"\"sid\": \"102\"" +
"}]" +
"}," +
"\"resultCode\": \"1\"" +
"}");
System.out.println("json对象:"+json2+"\n");
System.out.println("json对象-->map对象:"+parseJSONstr2Map(json2)+"\n");
System.out.println("map对象-->json对象:"+JSONObject.fromObject(parseJSONstr2Map(json2)).toString()+"\n");
for(String key : parseJSONstr2Map(json2).keySet()){
System.out.println("我是KEY:" + key);
System.out.println("我是value:" + parseJSONstr2Map(json2).get(key));
}
}
需要导入依赖:
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>**加粗样式**