繁体   English   中英

如何从很大的JSON数组中获取数据?

[英]How to get data from a very big JSON array?

我正在为游戏使用API​​,它返回一个很大的JSON对象。 问题是,当我尝试访问其中的整数时,它不起作用,并在logcat中以橙色文本system.err显示JSON对象的一部分。 我如何访问此数组中想要的任何值?

下面显示了json对象的代码和结构。

private class getGame extends AsyncTask<Integer, Integer, String>{

        Context context;
        private getGame(Context context) {
            this.context = context.getApplicationContext();
        }

        String response;


        @Override
        protected String doInBackground(Integer... params) {
            HttpClient client = new DefaultHttpClient();
            String geturl = "https://eu.api.pvp.net/api/lol/tr/v1.3/game/by-summoner/1795120/recent?api_key=cea2196c-6a12-474f-8f6d-52ad5e612cbc";
            HttpGet get = new HttpGet(geturl);
            HttpResponse responseGet = null;
            try {
                responseGet = client.execute(get);
                HttpEntity resEntityGet = responseGet.getEntity();
                response = EntityUtils.toString(resEntityGet);
                JSONObject jsonObj = new JSONObject(response);
                JSONObject gamesObj = jsonObj.getJSONObject("games");
                JSONObject game0 = jsonObj.getJSONObject("0");
                Log.e("test", ""+game0.getInt("gameId"));
                return "";

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }

是Json对象和logcat警告的结构,示例jsonobject在此处

尝试这个..

{                // JSONObject
  "games": [     // JSONArray

改变这个

JSONObject gamesObj = jsonObj.getJSONObject("games");

JSONArray gamesObj = jsonObj.getJSONArray("games").getJSONObject(0).getJSONArray("fellowPlayers");
JSONObject game0 = jsonObj.getJSONObject(0);

进一步澄清

JSONObject jsonObj = new JSONObject(response);
JSONArray gamesarray = jsonObj.getJSONArray("games");
JSONObject game0 = gamesarray.getJSONObject(0);
JSONArray fellowarray = game0.getJSONArray("fellowPlayers");
JSONObject fellow0 = fellowarray.getJSONObject(0);
Log.e("test", ""+fellow0.getInt("gameId"));

如果您真的想解析很大的json,请使用允许流传输的json库。

http://wiki.fasterxml.com/JacksonInFiveMinutes (请参见流API示例)

杰克逊确实允许流媒体。

如果您只是不知道如何解析数组,则应该更改您的问题。

如果只想解析数组,则必须验证是否存在{或[这是对象还是数组。 您还可以通过使用以下命令验证结果是数组还是对象

JSONObject json;
Object     info;
JSONArray  infoJsonArray;
JSONObject infoObject;
json = new JSONObject(str);

Object info= json.get("games");
if (info instanceof JSONArray) {
// It's an array
infoJsonArray = (JSONArray)info;
}
else if (info instanceof JSONObject) {
// It's an object
infoObject = (JSONObject)info;
} else {
// It's something else, like a string or number
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM