Advertisement
Guest User

Untitled

a guest
Jul 27th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. public class JsonParser {
  2.  
  3. private List<String> pathList;
  4. private String json;
  5.  
  6. public JsonParser(String json) {
  7. this.json = json;
  8. this.pathList = new ArrayList<String>();
  9. setJsonPaths(json);
  10. }
  11.  
  12. public List<String> getPathList() {
  13. return this.pathList;
  14. }
  15.  
  16. private void setJsonPaths(String json) {
  17. this.pathList = new ArrayList<String>();
  18. JSONObject object = new JSONObject(json);
  19. String jsonPath = "$";
  20. if(json != JSONObject.NULL) {
  21. readObject(object, jsonPath);
  22. }
  23. }
  24.  
  25. private void readObject(JSONObject object, String jsonPath) {
  26. Iterator<String> keysItr = object.keys();
  27. String parentPath = jsonPath;
  28. while(keysItr.hasNext()) {
  29. String key = keysItr.next();
  30. Object value = object.get(key);
  31. jsonPath = parentPath + "." + key;
  32.  
  33. if(value instanceof JSONArray) {
  34. readArray((JSONArray) value, jsonPath);
  35. }
  36. else if(value instanceof JSONObject) {
  37. readObject((JSONObject) value, jsonPath);
  38. } else { // is a value
  39. this.pathList.add(jsonPath);
  40. }
  41. }
  42. }
  43.  
  44. private void readArray(JSONArray array, String jsonPath) {
  45. String parentPath = jsonPath;
  46. for(int i = 0; i < array.length(); i++) {
  47. Object value = array.get(i);
  48. jsonPath = parentPath + "[" + i + "]";
  49.  
  50. if(value instanceof JSONArray) {
  51. readArray((JSONArray) value, jsonPath);
  52. } else if(value instanceof JSONObject) {
  53. readObject((JSONObject) value, jsonPath);
  54. } else { // is a value
  55. this.pathList.add(jsonPath);
  56. }
  57. }
  58. }
  59.  
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement