从Android上的URL简单地parsingJSON,并在ListView中显示

我试图parsing从我的Android应用程序中的URL获取的JSON结果…

我已经在互联网上尝试了一些例子,但无法使其工作。 JSON数据如下所示:

[ { "city_id": "1", "city_name": "Noida" }, { "city_id": "2", "city_name": "Delhi" }, { "city_id": "3", "city_name": "Gaziyabad" }, { "city_id": "4", "city_name": "Gurgaon" }, { "city_id": "5", "city_name": "Gr. Noida" } ] 

获取URL并parsingJSON数据的最简单方法是在列表视图中显示它

Solutions Collecting From Web of "从Android上的URL简单地parsingJSON,并在ListView中显示"

你可以使用AsyncTask ,你必须自定义以适应你的需求,但是像下面这样


asynchronous任务有三个主要方法:

  1. onPreExecute() – 最常用于设置和启动进度对话框

  2. doInBackground() – build立连接并从服务器接收响应(不要尝试为GUI元素分配响应值,这是常见错误,不能在后台线程中完成)。

  3. onPostExecute() – 这里我们不在后台线程中,所以我们可以用响应数据做用户界面操作,或者直接将响应分配给特定的variablestypes。

首先,我们将启动这个类,初始化一个String来保存方法以外的结果,但在类内部,然后运行onPreExecute()方法来设置一个简单的进度对话框。

 class MyAsyncTask extends AsyncTask<String, String, Void> { private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this); InputStream inputStream = null; String result = ""; protected void onPreExecute() { progressDialog.setMessage("Downloading your data..."); progressDialog.show(); progressDialog.setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface arg0) { MyAsyncTask.this.cancel(true); } }); } 

然后,我们需要build立连接以及我们如何处理响应:

  @Override protected Void doInBackground(String... params) { String url_select = "http://yoururlhere.com"; ArrayList<NameValuePair> param = new ArrayList<NameValuePair>(); try { // Set up HTTP post // HttpClient is more then less deprecated. Need to change to URLConnection HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url_select); httpPost.setEntity(new UrlEncodedFormEntity(param)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); // Read content & Log inputStream = httpEntity.getContent(); } catch (UnsupportedEncodingException e1) { Log.e("UnsupportedEncodingException", e1.toString()); e1.printStackTrace(); } catch (ClientProtocolException e2) { Log.e("ClientProtocolException", e2.toString()); e2.printStackTrace(); } catch (IllegalStateException e3) { Log.e("IllegalStateException", e3.toString()); e3.printStackTrace(); } catch (IOException e4) { Log.e("IOException", e4.toString()); e4.printStackTrace(); } // Convert response to string using String Builder try { BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8); StringBuilder sBuilder = new StringBuilder(); String line = null; while ((line = bReader.readLine()) != null) { sBuilder.append(line + "\n"); } inputStream.close(); result = sBuilder.toString(); } catch (Exception e) { Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString()); } } // protected Void doInBackground(String... params) 

最后,在这里我们将parsing返回值,在这个例子中它是一个JSON数组,然后closures对话框:

  protected void onPostExecute(Void v) { //parse JSON data try { JSONArray jArray = new JSONArray(result); for(i=0; i < jArray.length(); i++) { JSONObject jObject = jArray.getJSONObject(i); String name = jObject.getString("name"); String tab1_text = jObject.getString("tab1_text"); int active = jObject.getInt("active"); } // End Loop this.progressDialog.dismiss(); } catch (JSONException e) { Log.e("JSONException", "Error: " + e.toString()); } // catch (JSONException e) } // protected void onPostExecute(Void v) } //class MyAsyncTask extends AsyncTask<String, String, Void> 
 JSONObject(html).getString("name"); 

如何获取htmlstring: 使用android发出HTTP请求

我会build议使用JSONParser类。 这非常容易使用。

 public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } // function get json from url // by making HTTP POST or GET method public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) throws IOException { // Making HTTP request try { // check for request method if(method == "POST"){ // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); }else if(method == "GET"){ // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (Exception ex) { Log.d("Networking", ex.getLocalizedMessage()); throw new IOException("Error connecting"); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } 

然后在你的应用程序中,创build这个类的一个实例。 如果需要,您可能想传递构造函数“GET”或“POST”。

 public JSONParser jsonParser = new JSONParser(); try { // Building Parameters ( you can pass as many parameters as you want) List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("name", name)); params.add(new BasicNameValuePair("age", 25)); // Getting JSON Object JSONObject json = jsonParser.makeHttpRequest(YOUR_URL, "POST", params); } catch (JSONException e) { e.printStackTrace(); } 

试试:

  // your get json request to server.. HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); if(entity != null){ JSONObject respObject = new JSONObject(EntityUtils.toString(entity)); String active = respObject.getString("active"); String name = respObject.getString("name"); String tab1_text = respObject.getString("tab1_text"); //.... } else{ //Do something here... } 

看到这个例子获取和分析来自服务器的JSON响应:

http://adblogcat.com/parse-json-data-from-a-web-server-and-display-on-listview/

 import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; public class GetJsonFromUrl { String url = null; public GetJsonFromUrl(String url) { this.url = url; } public String GetJsonData() { try { URL Url = new URL(url); HttpURLConnection connection = (HttpURLConnection) Url.openConnection(); InputStream is = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } line = sb.toString(); connection.disconnect(); is.close(); sb.delete(0, sb.length()); return line; } catch (Exception e) { return null; } } } 

这个类用于发布数据

 import android.util.Log; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import javax.net.ssl.HttpsURLConnection; /** * Created by user on 11/2/16. */ public class sendDataToServer { public String postdata(String requestURL,HashMap<String,String> postDataParams){ try { String response = ""; URL url = new URL(requestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(getPostDataString(postDataParams)); writer.flush(); writer.close(); os.close(); String line; BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line=br.readLine()) != null) { response+=line; } Log.d("test", response); return response; }catch (Exception e){ return e.toString(); } } public String postjson(String url,String json){ try { URL obj = new URL(url); HttpURLConnection con= (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("Accept", "application/json"); String urlParameters = ""+json; // Send post request con.setDoOutput(true); con.setDoInput(true); con.setRequestProperty("Content-Type", "application/json"); OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream()); wr.write(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result System.out.println(response.toString()); return response.toString(); }catch(Exception e){ return e.toString(); } } private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for(Map.Entry<String, String> entry : params.entrySet()){ if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } return result.toString(); } /* public String postdata(String url) { }*/ } 
 HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(url)); HttpResponse response = client.execute(request); BufferedReader in = new BufferedReader(new InputStreamReader(response .getEntity().getContent())); String line = ""; while ((line = in.readLine()) != null) { JSONObject jObject = new JSONObject(line); if (jObject.has("name")) { String temp = jObject.getString("name"); Log.e("name",temp); } }