Skip to content

Instantly share code, notes, and snippets.

@pingjiang
Created January 12, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pingjiang/27ad2c633ebd2071af9e to your computer and use it in GitHub Desktop.
Save pingjiang/27ad2c633ebd2071af9e to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonQueryEngine {
public static List<String> getExpressionValues(String expression, String propertySeperator, JSONObject jsonObject) throws Exception{
String[] nodesList = expression.split(propertySeperator);//Splitting each property in expression
List<String> expressionValues = new ArrayList<String>();
List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
//Temporary Objects for swapping (Won't consume much memory as the values are pointers)
List<JSONObject> intermediateJsonObjects = new ArrayList<JSONObject>();
jsonObjects.add(jsonObject);
//Populating targeted Json
for (int i = 0; i < nodesList.length - 1; i++) {
for (JSONObject propertyObject : jsonObjects) {
intermediateJsonObjects.addAll(getNodeJsonObjects(nodesList[i], propertyObject));
}
jsonObjects.clear();
jsonObjects.addAll(intermediateJsonObjects);
intermediateJsonObjects.clear();
}
//Populating targeted Json Values
for (JSONObject propertyObject : jsonObjects) {
expressionValues.add(propertyObject.get(nodesList[nodesList.length - 1]).toString());
}
return expressionValues;
}
private static List<JSONObject> getNodeJsonObjects(String node, JSONObject parentObject) throws Exception{
List<JSONObject> nodeJsonObjects = new ArrayList<JSONObject>();
Object object = parentObject.get(node);
if(object instanceof JSONObject)
nodeJsonObjects.add((JSONObject)object);
else{
JSONArray jsonArray = (JSONArray)object;
for (int i = 0; i < jsonArray.length(); i++) {
nodeJsonObjects.add((JSONObject)jsonArray.get(i));
}
}
return nodeJsonObjects;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment