How to Json Parsing in android

前端 未结 4 1924
遇见更好的自我
遇见更好的自我 2021-01-07 08:18

http://docs.blackberry.com/sampledata.json

This is my web service and I want to parse and retrieve vehicleType, vehicleColor, fuel, name, experiencePoints, treadType

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-07 08:37

    The given url returns a JSONArray, so the method getJSONFromUrl should return JSONArray..

    try {
            HttpParams params = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(params, Constants.CONNECTION_TIME_OUT);
            HttpConnectionParams.setSoTimeout(params, 0);
            HttpClient httpClient = new DefaultHttpClient(params);
    
            //prepare the HTTP GET call 
            HttpGet httpget = new HttpGet(urlString);
            //get the response entity
            HttpEntity entity = httpClient.execute(httpget).getEntity();
    
            if (entity != null) {
                //get the response content as a string
                String response = EntityUtils.toString(entity);
                //consume the entity
                entity.consumeContent();
    
                // When HttpClient instance is no longer needed, shut down the connection manager to ensure immediate deallocation of all system resources
                httpClient.getConnectionManager().shutdown();
    
                //return the JSON response
                JSONArray array = new JSONArray(response.trim());
                    for(int i = 0 ; i < array.length() ; i++) { //get the current JSON object
                        JSONObject object = (JSONObject) array.get(i);
                        String vehicleType = object.getString("vehicleType");
                        ......
                     }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    

提交回复
热议问题