我有一个带有 2 个带有 JSONObjects 的 JSONArrays。我想知道如何访问位于 JSONObject 中的 JSONArray 中的 JSONObjects?(JSON开始!
澄清(即使我对写这个感到困惑)
我首先得到一个 JSONObject此对象包含 2 个 JSONArrays这 2 个数组具有 X 和 Y 数量的 JSONObject。
我如何达到"最深"的 JSONObjects?如何"展开"第一个 JSONObject 以获得前 2 个 JSONArray?
有什么提示或技巧可以分享吗?
Yuo可以使用这样的东西new JSONObject(json).getJSONArray(arrayname1).getJSONObject(positionx)
。
这里json
是 JSON 响应字符串。 arrayname1
是第一个数组的名称。poitionx
是X JSONObjects的任何位置。
同样,您可以将new JSONObject(json).getJSONArray(arrayname2).getJSONObject(positiony)
用于另一个。
有什么提示或技巧可以分享吗?
是的,使用像谷歌的GSON这样的JSON库。
以下是使用它的参考。 http://java.sg/parsing-a-json-string-into-an-object-with-gson-easily/
祝你好运!
这是一个例子。假设我们有一个JSONObject"Space",有两个数组:一个和两个。
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("url");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
JSONObject json=new JSONObject(result);
JSONObject resp= (JSONObject) json.get("response");
JSONObject Space=resp.getJSONObject("Space");
JSONArray One=Space.getJSONArray("one");
int Length=One.length();
for(int i=0;i<length;i++)
{
JSONObject item = (JSONObject) items.get(j);
String x=item.getString("x);
String y=item.getString("y");
System.out.println("x = "+x+" , y = "+y);
}
以同样的方式,您可以使用第二个阵列。