Json DFS parse(PG)

    xiaoxiao2021-12-15  44

    JSON format Data { "GB": { "birmington": {"apple": "20", "google": "50", ....},. more info on 1point3acres.com "london": {"apple": "110", "google": "70", ....}, ..... },  "US": { "new york": {"apple": "100", "google": "200", ....}, "san francisco": {"apple": "150", "google": "50", ....}, }, .... .... } columns: ['country', 'city', 'store', 'rev'] output: [{"city": "london", "country": "GB", "rev": "70", "store": "google"}, {"city": "london", "country": "GB", "rev": "110", "store": "apple"}, {"city": "birmington", "country": "GB", "rev": "50", "store": "google"}, {"city": "birmington", "country": "GB", "rev": "20", "store": "apple"}, {"city": "san francisco", "country": "US", "rev": "50", "store": "google"}, ....] m cols n row input: JSON apiData, String[] columns output: List<Hashtable<String, String>> class JSON { // base class for json data type public JSON(String json); // constructor public String toString(); // convert json data type to string that can be printed public String type(); // return type. 1point 3acres 璁哄潧 } class JSONMapping extend JSON { public JSON get(String key); // return value corresponding to the key public String[] keys(); // return all the keys public String type() {return "JSONMapping";} } class JSONString extend JSON { public String value(); // return the stringpublic String type() { return "JSONString"; } 

    题目描述:输入jsonData 和columns数组, 将折叠过后的json数据展开变成一个扁平化的json数据, input: JSON apiData, String[] columns, output: List

    public List<HashTable<String,String>> getResults(Json apiData,String columns){ List<HashTable<String,String>> res = new ArrayList<>(); if(apiData==null||columns==null) return res; dfs(apiData,columns,res,0); return res; } public List<HashTable<String,String>> dfs(Json apiData,String[] columns,List<HashTable<String,String>> res, int index,HashTable<String,String> path){ //base case的递归出口 第一种情况是apiData返回的是jsonString这个时候,尽管columns数组还没有走到尽头,但是该层的结果集已经不能继续往下dfs了,所以我们需要将该结果加进results里面,之后进行backtracking 因为dfs这一支走完了之后,需要删掉最后一个hashtable<String,String>,继续保留原来的path走另外一个分支 if(apidata.type()==jsonString){ path.put(columns[index],keys[i]); res.add(new HashMap<String,String>(path)) path.remove(columns[i]); } //base case 当递归的深度达到 columns的length的时候,就可以将path加入到results里面 if(index==columns.length){ res.add(new HashTable<StringString> path); } String[] keys = apidata.keys()// //用APi所给的方法,去取得该jsonMapping类里面所对应的keys数组 ,对所有的keys进行遍历,讲改keys[i] 与columns[index]一一对饮 for(int i=0;i<keys.length,i++){ //为什么for循环里面是一个dfs函数,因为每次讲对应的key value pair放进HashTable里面的时候,相当于刚走完一个root节点,之后还要对该root节点调用dfs函数 沿着分支往下走 backtrakcing的时候要remove掉column[index]的原因是因为 for example:当我们country对应的US走完了之后,我们要走GM所以US的应该删了 path.put(columns[index],keys[i]) dfs(apiData.get(key[i]),columns,res,index+1,path path.remove(columns[index]); } if(apiData.type()){ JSON json = apiData.get(column); String[] keys= apiData.keys; }_ } }_
    转载请注明原文地址: https://ju.6miu.com/read-1000310.html

    最新回复(0)