public class MapModel extends HashMap<String, Object> { public void Add(MapModel other) { if (other == null) return; for (String key : other.keySet()) { this.put(key, other.get(key)); } } public static MapModel LoadFromUrl(String UrlQuery) { MapModel ret = new MapModel(); List<String> list = MyString.MySplit(UrlQuery, '&'); for (String item : list) { List<String> kv = MyString.MySplit(item, '='); ret.Tourch(kv.get(0), kv.get(1)); } return ret; } public void Tourch(String KeyPath, String Value) { if (this.containsKey(KeyPath)) return; int sepIndex = GetNextCharIndex_SkipQuotes(KeyPath, 0, '.', '['); if (sepIndex >= KeyPath.length()) { this.put(KeyPath, Value); return; } char chr = KeyPath.charAt(sepIndex); String objKey = KeyPath.substring(0, sepIndex); if (chr == '.') { if (this.containsKey(objKey) == false) { this.put(objKey, new MapModel()); } MapModel vv = (MapModel) this.get(objKey); vv.Tourch(KeyPath.substring(sepIndex + 1), Value); } else { if (this.containsKey(objKey) == false) { this.put(objKey, new ArrayList<Object>()); } List<Object> list = (List<Object>) this.get(objKey); int nextDotIndex = KeyPath.indexOf('.', sepIndex + 1); if (nextDotIndex < 0) { nextDotIndex = KeyPath.length(); } List<String> aryIndexs_Strings = MySplit(TrimWithPair(Slice(KeyPath, sepIndex, nextDotIndex).replace(" ", "").replace("][", ","), "[", "]"), ','); List<Integer> aryIndexs = new ArrayList<Integer>(); for (String k : aryIndexs_Strings) { aryIndexs.add(MyObject.AsInt(k)); } MapModel vv = (MapModel) PatchArrayLevels(list, aryIndexs, Value, KeyPath.indexOf('.', sepIndex + 1) > 0, 0); if (vv != null) { vv.Tourch(Slice(KeyPath, nextDotIndex + 1), Value); return; } } } Object PatchArrayLevels(List<Object> list, List<Integer> indexs, String Value, boolean NextIsDict, int level) { int index = indexs.get(level); if (level >= (indexs.size() - 1)) { if (NextIsDict) { for (int i = list.size(); i <= index; i++) { list.add(new MapModel()); } list.set(index, new MapModel()); return list.get(index); } else { for (int i = list.size(); i <= index; i++) { list.add(null); } list.set(index, Value); return null; } } for (int i = list.size(); i <= index; i++) { list.add(new ArrayList<Object>()); } return PatchArrayLevels((List<Object>) list.get(index), indexs, Value, NextIsDict, level + 1); } }
具体实现参考开源项目的实现,项目地址: