对Array Android的JSON RPC响应

时间:2018-03-01 23:58:38

标签: java android json json-rpc

我设法获得json rpc请求的结果,如下所示:

{“id”:1,“jsonrpc”:“2.0”,“result”:{“channels”:[{“channel”:“Channel A”,“channelid”:2165,“label”:“Channel” “},{”频道“:”频道B“,”channelid“:748,”标签“:”频道B“}等。

我想将响应解析为一个数组,我可以在循环的每次迭代中读取channel,channelid和label。但没有成功。

非常感谢任何帮助。

很抱歉没有经验丰富的编程,它是自学成才的

json rpc请求代码:

  String groupchannelsurl = "http://192.168.2.100:8080/jsonrpc?request={\"jsonrpc\": \"2.0\", \"method\": \"PVR.GetChannels\", \"params\": {\"channelgroupid\" : 9,\"properties\":[\"channel\"]}, \"id\": 1 }";
    
        RequestQueue queue = Volley.newRequestQueue(this);  
        JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, groupchannelsurl, null,
                new Response.Listener<JSONObject>()
                {
                    @Override
                    public void onResponse(JSONObject response) {
                        // display response
                        Log.d("Response", response.toString());
                      

                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("Error.Response", error.toString());
                    }
                }
        );


        queue.add(getRequest);

2 个答案:

答案 0 :(得分:0)

如果您遇到困难,Android Developer文档非常好。

JSONObject -  https://developer.android.com/reference/org/json/JSONObject.html

JSONArray - https://developer.android.com/reference/org/json/JSONArray.html

@Override
public void onResponse(JSONObject response) {
    JSONArray channels = response.getJSONObject("result").getJSONArray("channels");
    for (int i = 0; i < channels.length(); i++) {
        JSONObject channel = channels.getJSONObject(i);
        String channelName = channel.getString("channel");
        int channelId = channel.getInt("channelid");
        String channelLabel = channel.getString("label");
        // ...
    }
}

希望这有帮助!

答案 1 :(得分:0)

您可以解析JSONObject,如下所示

private void parseJsonObject(JSONObject responseObject) throws JSONException {

    String id = responseObject.getString("id");

    JSONArray jsonArray = responseObject.optJSONArray("channels");
    if (jsonArray != null) {

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

            JSONObject arrayObject = (JSONObject) jsonArray.get(i);

            String channel = arrayObject.getString("channel");
            String channelId = arrayObject.getString("channelid");


        }


    }


}