Skip to content

Instantly share code, notes, and snippets.

@ludorumjeoun
Created March 4, 2016 09:14
Show Gist options
  • Save ludorumjeoun/b82ef8c09ddae402de27 to your computer and use it in GitHub Desktop.
Save ludorumjeoun/b82ef8c09ddae402de27 to your computer and use it in GitHub Desktop.
Finder.java
package com.example.util;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Finder extends LinkedHashMap<String, Object> {
public Finder(Map<String, Object> origianl) {
super(origianl);
}
public Finder() {
}
public Finder findChild(String path) {
Map map = find(path);
return new Finder(map);
}
public <T> T find(String path, T defaultValue) {
Object ele = (defaultValue instanceof String) ? findAsString(path) : find(path);
ele = ele != null ? ele : defaultValue;
return (T) ele;
}
public String findAsString(String path) {
Object obj = find(path);
return obj != null ? String.valueOf(obj) : null;
}
public static final Pattern ROUTE = Pattern.compile("([^\\.\\[\\]]+|\\[\\d+\\])");
public <T> T find(String path) {
Object ele = this;
final Matcher matcher = ROUTE.matcher(path);
Iterator<String> it = new Iterator<String>() {
@Override
public boolean hasNext() {
return matcher.find();
}
@Override
public String next() {
return matcher.group();
}
@Override
public void remove() {
}
};
while (it.hasNext()) {
String key = it.next();
if (key.startsWith("[")) {
ele = ((List) ele).get(Integer.parseInt(key.substring(1, key.length() - 1)));
} else {
ele = ((Map) ele).get(key);
}
if (ele == null) {
break;
}
}
return (T) ele;
}
public static Finder fromJSON(JSONObject object) throws JSONException {
return new Finder(toMap(object));
}
protected static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new LinkedHashMap<>();
Iterator<String> keysItr = object.keys();
while (keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if (value instanceof JSONArray) {
value = toList((JSONArray) value);
} else if (value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
protected static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if (value instanceof JSONArray) {
value = toList((JSONArray) value);
} else if (value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment