目前在项目中遇到一个问题,就是需要把第三方的接口数据保存到本地数据库中,但是不确定第三方接口返回的数据格式,该咋办呢?
现在有两个问题需要处理:
对于第一个问题的目前处理办法是 用JSONObject的方式处理,xml转成json再处理,统一用jsonobject来处理
对于第二个问题的处理办法是用一个配置方案,指定json的各个属性对应表的哪个column上,例如对于原始json A{"a":"1","b":"2"},
我们的配置为{"colunm1":"a","colunm2":"b"},意思是说把结果中的a属性对应的值1放进表的colunm1上,把属性b对应的值放在column2上。
但是很多情况下,json数据不是简单的一维的,没有jsonArray的json可以根据属性路径能找到唯一的一个值,但是在有jsonArray的json中无法通过路径找到jsonArray中的具体的一个,所以现在的问题是把有jsonArray的json转成一维的jsonObject的list
原始json {"a":1,"b":[{"e":4,"f":5},{"e":6,"f":7}]}
解析后的结果是
[{"a":1,"e":4,"f":5},{"a":1,"e":6,"f":7}],然后在遍历该list中的每一个一维的jsonObject,根据配置信息保存到数据库中
1 核心方法,就是把指定的key拿出来,再从父层删除key对应的值,值再和父层合并。
//另外一种方案,就是结果数据转成一维表格形式 public static Listaction(JSONObject jsonObject, String detailKey){ Object detailObj = jsonObject.get(detailKey); List allJSONObjectList = new ArrayList<>(); if(detailObj!=null){ JSONObject resultJsonObject,detailObjOne; jsonObject.remove(detailKey); if(detailObj instanceof JSONArray){ JSONArray detailArray = (JSONArray)detailObj; for(int i=0;i //把一个json中的key加上指定的前缀 private static JSONObject action1(JSONObject jsonObject,String detailKey){ Iterator iterator = jsonObject.keys(); JSONObject object = new JSONObject(); while(iterator.hasNext()){ String key = (String) iterator.next(); object.put(detailKey+"_"+key,jsonObject.get(key)); } return object; }// 迭代方法
public static void fun(JSONObject obj,int i,int len,String [] p,Listb) { if (i >= len) { return; } else { for (JSONObject jsonObject : action(obj, p[i++])) { if (i == len - 1) { b.addAll(action(jsonObject, p[i])); } else { fun(jsonObject, i,len,p, b); } } } } // 最终方法调用
String json = "{\"r\":{\"A\":{\"A1\":1},\"a\":1,\"b\":[{\"c\":2,\"d\":[{\"e\":4,\"f\":5,\"A\":\"AA1\"},{\"e\":6,\"f\":7,\"A\":\"AA12\"},{\"e\":66,\"f\":76,\"A\":\"AA13\"}]},{\"c\":3,\"d\":[{\"e\":8,\"f\":9,\"A\":\"AA14\"},{\"e\":10,\"f\":11,\"A\":\"AA15\"}]}]},\"m\":\"ok\"}"; JSONObject jsonObject = JSONObject.fromObject(json); String detail = "r.r_b.r_b_d";// 指定已知的发散点 String[] p = detail.split("\\."); Listb = new ArrayList<>(); fun(jsonObject,0,p.length,p,b); System.out.println(b); 原始json
{"r":{"A":{"A1":1},"a":1,"b":[{"c":2,"d":[{"e":4,"f":5,"A":"AA1"},{"e":6,"f":7,"A":"AA12"},{"e":66,"f":76,"A":"AA13"}]},{"c":3,"d":[{"e":8,"f":9,"A":"AA14"},{"e":10,"f":11,"A":"AA15"}]}]},"m":"ok"}
处理结果
[
{"m":"ok","r_A":{"A1":1},"r_a":1,"r_b_c":2,"r_b_d_e":4,"r_b_d_f":5,"r_b_d_A":"AA1"},
{"m":"ok","r_A":{"A1":1},"r_a":1,"r_b_c":2,"r_b_d_e":6,"r_b_d_f":7,"r_b_d_A":"AA12"},
{"m":"ok","r_A":{"A1":1},"r_a":1,"r_b_c":2,"r_b_d_e":66,"r_b_d_f":76,"r_b_d_A":"AA13"},
{"m":"ok","r_A":{"A1":1},"r_a":1,"r_b_c":3,"r_b_d_e":8,"r_b_d_f":9,"r_b_d_A":"AA14"},
{"m":"ok","r_A":{"A1":1},"r_a":1,"r_b_c":3,"r_b_d_e":10,"r_b_d_f":11,"r_b_d_A":"AA15"}
]