使用未确定数量的子节点解析JSON对象

我使用Dropbox API,我想从json对象获取文件夹和路径。 但是我遇到了问题,因为有一些子节点被破坏了。 我该如何解析这样的东西?

编辑

JSONObject表示一个目录。 顶级文件夹由json对象表示。 在该对象内是子文件夹。 他们每个人都有JSONobject,在每个jsonobject中都有一个数组,代表子文件夹的子文件夹。 所以我不知道json的完整结构

我只是遇到了同样的问题,我写了一个带有递归算法的类,它通过并搜索特定的id ..似乎工作正常,随意尝试一下!

import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class JsonReference { Object data; public JsonReference(String buildFromString){ try { data = new JSONObject(buildFromString); } catch (JSONException e) { e.printStackTrace(); } if(data == null){ try { data = new JSONArray(buildFromString); } catch (JSONException e) { e.printStackTrace(); } } } public Object getAbstractJsonObject(){ return data; } public List parseForData(String data,boolean removeDuplicates){ Traverser valFinder = new Traverser(0); valFinder.setValues(data, removeDuplicates); valFinder.traverseForStringValue(this.data); return valFinder.foundInstances; } class Traverser{ List foundInstances = new ArrayList(); String value; boolean removeDuplicates; public Traverser(int type){ } public void setValues(String value,boolean removeDuplicates){ this.value = value; this.removeDuplicates = removeDuplicates; } public void traverseForStringValue(Object root){ if(root == null){ return; } else if(root instanceof JSONObject){ JSONObject self = (JSONObject)root; //if the key exists in this object.. save it! if(self.has(value)){ try { if(!removeDuplicates || notRepeat(self.getString(value))) foundInstances.add(self.getString(value)); } catch (JSONException e) { e.printStackTrace(); } return; } //otherwise, see if you can dive deeper.. JSONArray names = self.names(); for(int i=0;i 

得到了这个回复来自https://stackoverflow.com/a/10593838/259889

 JSONObject jObject = new JSONObject(contents.trim()); Iterator keys = jObject.keys(); while( keys.hasNext() ){ String key = (String)keys.next(); if( jObject.get(key) instanceof JSONObject ){ // do your stuff } } 

对于带有节点的JsonObject ,您可以执行以下操作:

 JsonObject jsonO = //get your JsonObject List keys = jsonO.keys(); List nodes = new ArrayList for(String k: keys){ nodes.add(jsonO.get(k)); } 

如果是JsonArray

 JSONArray jsonA = //get Your JsonArray List nodes = new ArrayList for (int i = 0; i < jsonA.length(); i++){ nodes.add(jsonA.get(i)); } 

或考虑使用GSON

它可能是你想要转换它的JSONArray。 如果你没有根据JSONObject中的id来提取值,那么它就是一个JSONArray。 你可以这样做:

 for (int i = 0; i < jsonArray.length(); i++) { whateverTheObjectIs = jsonArray.getObject(i); }