package com.yinhai.bigdata.etl;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject;
import java.util.*;
public class demo {
public static void main(String[] args){ Map data_test_1=new HashMap(); data_test_1.put("k1", "kaaa"); data_test_1.put("k2", "kbbb");
Map data_test_2=new HashMap(); data_test_2.put("k3", "kccc"); data_test_2.put("k4", "kddd");
List list_test_1=new ArrayList(); list_test_1.add(data_test_1); list_test_1.add(data_test_2);
Map data_test_3=new HashMap(); data_test_3.put("m1", list_test_1); data_test_3.put("m2", 1); System.out.println(data_test_3); //{m1=[{k1=kaaa, k2=kbbb}, {k3=kccc, k4=kddd}], m2=1}
String str1=JSON.toJSONString(data_test_3); System.out.println(str1); //{"m1":[{"k1":"kaaa","k2":"kbbb"},{"k3":"kccc","k4":"kddd"}],"m2":1}
JSONObject obj=JSON.parseObject(str1); System.out.println(obj); //{"m1":[{"k1":"kaaa","k2":"kbbb"},{"k3":"kccc","k4":"kddd"}],"m2":1}
List list_1= (List) obj.get("m1"); System.out.println(list_1); //[{"k1":"kaaa","k2":"kbbb"},{"k3":"kccc","k4":"kddd"}]
Map data_map_4= (Map) list_1.get(1); System.out.println(data_map_4); //{"k3":"kccc","k4":"kddd"} System.out.println(data_map_4.get("k3")); //kccc
//这种也可以 Map param = JSON.parseObject(str1, HashMap.class); System.out.println(param); //{m1=[{"k1":"kaaa","k2":"kbbb"},{"k3":"kccc","k4":"kddd"}], m2=1} List list_2= (List) param.get("m1"); System.out.println(((Map)list_2.get(0)).get("k1")); //kaaa
//其实上面生成的已经完全够用了, //这里我用java把上面的obj遍历了一下,其实没必要 //这里用递归 就可以解决全部的嵌套 这里里面全是map Map res=new HashMap();//用来盛放解析的map Set<Map.Entry<String,Object>> entrySet=obj.entrySet(); for(Map.Entry<String,Object> e:entrySet){ String key=e.getKey().toString(); Object value= e.getValue(); if(value instanceof List){ List li= (List) value; List<Map> newArr=new ArrayList<Map>(); for (int i=0;i<li.size();i++){ Map li_map=new HashMap(); String str2=JSON.toJSONString(li.get(i)); JSONObject ja=JSON.parseObject(str2); Set<Map.Entry<String,Object>> entrySet1=ja.entrySet(); for(Map.Entry<String,Object> e1:entrySet1) { String key1 = e1.getKey().toString(); Object value1 = e1.getValue(); li_map.put(key1, value1); } newArr.add(li_map); } res.put(key,newArr); continue; }
res.put(key, value); }
System.out.println(res); //{m1=[{k1=kaaa, k2=kbbb}, {k3=kccc, k4=kddd}], m2=1}
}
}
|