Volley JSONObject请求解析响应未返回任何值

时间:2019-04-09 10:51:02

标签: android json android-volley

我有一个RESTful API在本地计算机上运行,​​该API根据请求返回JSON响应(实际上,此JSON是nodejs Soap客户端请求的响应)。对于这种特殊情况,我从Android客户端收到POST请求,并返回以下响应:

{
    QueryAcctBalResponse: {
        BalExDtoList: {
            BalExDto: [{
                BalID: "xxxx",
                AcctResID: "xxxx",
                AcctResName: "xxxx",
                BalType: "xxxx",
                Balance: "xxxx",
                EffDate: "xxxx",
                ExpDate: "xxxx",
                UpdateDate: "xxxx"
            }, {
                BalID: "yyyy",
                AcctResID: "yyyy",
                AcctResName: "yyyy",
                BalType: "yyyy",
                Balance: "yyyy",
                EffDate: "yyyy",
                ExpDate: "yyyy",
                UpdateDate: "yyyy"
            }]
        }
    }
}

问题是每次我尝试解析该响应并在android中显示此信息时(尤其是“ AcctResName”)。我得到 org.json.JSONException:BalExDto没有值。我在Android中使用Volley Libray解析Json,然后使用Jsonobject请求。

请求代码。

JsonObjectRequest sq = new JsonObjectRequest(Request.Method.POST, balanceUrl, request, new Response.Listener<JSONObject>() {

    @Override
    public void onResponse(JSONObject response) {

        try {
            JSONArray jsonArray = response.getJSONArray("BalExDto");
            for (int i = 0; i < jsonArray.length(); i++){
                JSONObject jsonObject=jsonArray.getJSONObject(i);
                Toast.makeText(CheckBalance.this, ""+jsonObject.get("AcctResName"), Toast.LENGTH_LONG).show();
            }

            pd.hide();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.d("Response", "Response_TAG: "+response);

    }

3 个答案:

答案 0 :(得分:1)

这是因为您没有JSON数组,而是拥有JSON对象。

首先,您需要从API响应中获取JSON对象,

JSONObject jsonObject = response.getJSONObject("QueryAcctBalResponse")

,该JSON对象内部是JSON数组。

JSONArray jsonArray = response.getJSONArray("BalExDtoList");

答案 1 :(得分:0)

BalExDto数组不是响应的直接子级。它位于BalExDtoList对象内部的QueryAcctBalResponse内部。您无法直接访问JSON中的任何节点,需要遍历完整路径,然后才能访问它们。

您需要获得如下所示的数组

JSONObject queryAcctBalResponse = response.getJSONObject("QueryAcctBalResponse");
JSONObject balExDtoList = queryAcctBalResponse.getJSONObject("BalExDtoList");
JSONArray jsonArray = balExDtoList.getJSONArray("BalExDto");

答案 2 :(得分:0)

该错误表明-您正在解析if (!global._babelPolyfill) { var a = require("babel-polyfill") } import {google} from 'googleapis' let bigQuery = google.bigquery("v2") describe('Run query with API', async () => { it('Run a query', async () => { let result = await test('panada') }) async function test(p1) { try { let query = `INSERT INTO \`project.dataset.Quincy\` (id, col) WITH array_to_loop_through AS ( SELECT id FROM UNNEST(GENERATE_ARRAY(1, 10, 1)) id ) SELECT id, CONCAT('Rank: ', CAST(id AS STRING)) FROM array_to_loop_through` let auth = getBasicAuthObj() auth.setCredentials({ access_token: "myAccessToken", refresh_token: "myRefreshToken" }) let request = { "projectId": "myProject", auth, "resource": { "projectId": "myProject", "configuration": { "query": { query, "useLegacySql": false }, "dryRun": false } } } console.log(`query is: ${query}`) let result = await callBQ(request) // debugger console.log(`Status is: ${result.data.status.state}`) } catch (err) { console.log("err", err) } } /** * Call BigQuery jobs.insert * @param request * @returns {Promise<*>} */ async function callBQ(request) { debugger // console.log("request", request) try { let result = await bigQuery.jobs.insert(request, request) console.log(`All good.....`) return result } catch (e) { console.log(`Failed to run query: ${e}`) } } /** * Create oAuth object * @returns {OAuth2Client} */ function getBasicAuthObj() { let clientId = 'myclientId' let clientSecret = 'mySecret' let redirectUrl = 'URL' return new google.auth.OAuth2( clientId, clientSecret, redirectUrl ) } }) 错误。 BalExDto不是BalExDto的直接子代。因此,您必须解析responseQueryAcctBalResponse,然后可以获得BalExDtoList。因为BalExDtoBalExDto内部,而BalExDtoListBalExDtoList内部。

QueryAcctBalResponse