1.以下是我封装的java类
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
*
* @author HeYunLai
* json工具类
*/
public class MissLiJsonUtil {
/**
*
* @param jsonData 字符串,格式如{"key":"val",,,}
* @return 根据传入json决定 Object
*/
public static Map jsonStringToMap(String jsonData) throws Exception{
JSONObject jsonObject = JSONObject.parseObject(jsonData);
Map<String,Object> hashMap = new HashMap<String,Object>();
for(String key : jsonObject.keySet()){
hashMap.put(key, jsonObject.getString(key));
}
return hashMap;
}
/**
* @param jsonData,格式如:[string,string,string]或[int,int,int,int]
* @return List<String>或List<Integer>
* @throws Exception
*/
public static List arrayStringToList(String jsonData)throws Exception{
JSONArray parseArray = JSON.parseArray(jsonData);
List<Object> list = new ArrayList<Object>();
for(Object object:parseArray){
list.add(object);
}
return list;
}
/**
*
* @param jsonData 嵌套的json数组,举个栗子:如传入[{},{}],则返回List<Map<>>,[]内可嵌套[]或{}
* @return 由传入jsonData决定
* @throws Exception
*/
public static List arrayNestArrayStringToList(String jsonData)throws Exception {
JSONArray parseArray = JSON.parseArray(jsonData);
List<Object> list= (List<Object>) recursiveTo(parseArray);
return list;
}
/**
*
* @param jsonData 字符串,格式如{key:{},key:{}},{}内可嵌套,[]或{}
* @return 由传入jsonData决定
*/
public static Map jsonNestJsonStringToMap(String jsonData)throws Exception {
JSONObject jsonObject = JSONObject.parseObject(jsonData);
Map<String,Object> hashMap = (Map<String, Object>) recursiveTo(jsonObject);
return hashMap;
}
/**
* 递归解析
* @param object
* @return
*/
private static Object recursiveTo(Object object)throws Exception {
if(object instanceof JSONObject){
Map<String, Object> map = new HashMap<>();
for(String key : ((JSONObject) object).keySet()){
map.put(key, recursiveTo(((JSONObject) object).get(key)));
}
return map;
}else if(object instanceof JSONArray){
List<Object> list = new ArrayList<>();
for(Object object2 : (JSONArray)object){
list.add(recursiveTo(object2));
}
return list;
}else{
return object;
}
}
/**
* 示例
* 测试
* @throws Exception
*/
public static void test() throws Exception{
List<String> list = MissLiJsonUtil.arrayStringToList("['1','2','3']");
Map<String,String> map = MissLiJsonUtil.jsonStringToMap("{\"he\":\"MissLi\"}");
List<Map<String,List<Map<String, String>>>> list2 = MissLiJsonUtil.arrayNestArrayStringToList("[{\"he\":[{\"li\":\"Miss\"}]}]");
Map<String, List<String>> map2 = MissLiJsonUtil.jsonNestJsonStringToMap("{\"he\":[\"MissLi\"]}");
for(int i = 0;i < list2.size();i++){
for (int j = 0; j < list2.get(i).get("he").size(); j++) {
System.out.println(list2.get(i).get("he").get(i).get("li"));
}
}
System.out.println(map2.get("he").get(0));
}
}