嵌套JSON使用Volley在android中解析URL

时间:2016-03-24 20:01:07

标签: android json android-volley

我第一次参与JSON Parsing。我正在尝试从URL检索数据并使用Volley解析它。但我没有得到数据。 我的代码:

{
 "CityCode": 374,
  "State": {
"StateCode": 29,
"CountryCode": 1,
"Country": {
  "CountryCode": 1,
  "IsdCode": "+91"
}
 },
 "Country": {
"CountryCode": 1,
"CountryName": "India",
"IsdCode": "+91"
 },
 "GPlaceId": "ChIJgeJXTN9KbDkRCS7yDDrG4Qw",
 "Latitude": 26.912434,
 "Longitude": 75.787271,
 "ActiveStatus": 1
}

我从网址获取的数据属于这种类型:

class AWS_CS
{
    protected $client;

    function connect($domain)
    {
        try{
            $csClient = CloudSearchClient::factory(array(
                            'key'          => 'YOUR_KEY',
                            'secret'      => 'YOUR_SECRET',
                            'region'     =>  'us-east-1'

                        ));

            $this->client = $csClient->getDomainClient(
                        $domain,
                        array(
                            'credentials' => $csClient->getCredentials(),
                            'scheme' => 'HTTPS'
                        )
                    );
        }
        catch(Exception $ex){
            echo "Exception: ";
            echo $ex->getMessage();
        }
        //$this->client->addSubscriber(LogPlugin::getDebugPlugin());        
    }
    function search($queryStr, $domain){

        $this->connect($domain);

        $result = $this->client->search(array(
            'query' => $queryStr,
            'queryParser' => 'lucene',
            'size' => 100,
            'return' => '_score,_all_fields'
            ))->toArray();

        return json_encode($result['hits']);
        //$hitCount = $result->getPath('hits/found');
        //echo "Number of Hits: {$hitCount}\n";
    }

    function deleteDocs($idArray, $operation = 'delete'){

        $batch = array();

        foreach($idArray as $id){
            //dumpArray($song);
            $batch[] = array(
                        'type'        => $operation,
                        'id'        => $id);                       
        }
        $batch = array_filter($batch);
        $jsonObj = json_encode($batch, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);

        print_r($this->client->uploadDocuments(array(
                        'documents'     => $jsonObj,
                        'contentType'     =>'application/json'
                    )));

        return $result['status'] == 'success' ? mb_strlen($jsonObj) : 0;
    }   
}

还请帮我解决嵌套的json解析,即如何检索变量“CountryCode”。

3 个答案:

答案 0 :(得分:0)

做这样的事情

String countryCode = jsonObject.getJSONObject("Country").getInt("CountryCode");

答案 1 :(得分:0)

如果我不记得错误的Volley最适合使用String&#39。你在整个地方都使用了double和int,所以为了让你的生活更轻松,你可以在JSON对象String中创建所有值。

这就是我这样做,然后从String转换为您在应用程序中需要的任何内容。例如,见下文。

{
"CityCode": "374",
"State": {
"StateCode": "29",
"CountryCode": "1",
"Country": {
"CountryCode": "1",
"IsdCode": "+91"
}
},
"Country": {
"CountryCode": "1",
"CountryName": "India",
"IsdCode": "+91"
},
"GPlaceId": "ChIJgeJXTN9KbDkRCS7yDDrG4Qw",
"Latitude": "26.912434",
"Longitude": "75.787271",
"ActiveStatus": "1"
}

答案 2 :(得分:0)

由于您不需要在请求中发送JSON对象,因此请使用定义hereStringRequest

RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://<your URL>";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
        new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {

        //I'm basically displaying the skeleton code. You have to put try/catch clauses when required.
        JSONObject json = new JSONObject(response);
        Integer cityCode = json.optInt("CityCode");
        String cityName = json.optString("CityName");
        JSONObject state = json.optJSONObject("State");
        String stateName = state.optString("StateName");
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        mTextView.setText("That didn't work!");
    }
});
// Add the request to the RequestQueue.
queue.add(stringRequest);