从 Android 上的 URL 简单解析 JSON 并显示在列表视图中

Posted

技术标签:

【中文标题】从 Android 上的 URL 简单解析 JSON 并显示在列表视图中【英文标题】:Simple parse JSON from URL on Android and display in listview 【发布时间】:2012-10-23 04:06:41 【问题描述】:

我正在尝试解析从我的 android 应用中的 URL 获取的 JSON 结果...

我在 Internet 上尝试了一些示例,但无法正常工作。 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 并解析 JSON 数据的最简单方法是在列表视图中显示它

【问题讨论】:

【参考方案1】:

您可以使用AsyncTask,您必须进行自定义以满足您的需求,但类似于以下内容


异步任务有三种主要方法:

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

    doInBackground() - 建立连接并从服务器接收响应(不要尝试将响应值分配给 GUI 元素,这是一个常见错误,无法在后台线程中完成)。

    onPostExecute() - 这里我们脱离了后台线程,所以我们可以对响应数据进行用户界面操作,或者简单地将响应分配给特定的变量类型。

首先我们将启动该类,初始化一个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);
            
        );
    

然后我们需要设置连接以及我们希望如何处理响应:

    @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)

最后,在这里我们将解析返回,在这个例子中它是一个 JSON 数组,然后关闭对话框:

    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>

【讨论】:

BufferedReader 实例应该是这样的:new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8)。 JSON的默认编码是UTF,为什么要转换成另一种非全局编码? @metallica 你是对的,我在我的一个应用程序中使用了这段代码,我没有阅读 JSON,我没有听懂。谢谢。 HttpClient 现已弃用,请使用 HttpURLConnection。 'ctrl+Q' on 'AsyncTask' 会给你很好的解释和例子 旧的正确答案,Volley Library 会为你做这一切,不再需要关心异步任务。 ref【参考方案2】:

我建议使用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;


然后在您的应用程序中,创建此类的一个实例。如果需要,您可能需要传递构造函数“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();

【讨论】:

这些变量不应该是静态的。同时使用这个类的多个实例会变得非常混乱。应该是私人的。也不要使用 == 来比较字符串:***.com/questions/513832/…【参考方案3】:
JSONObject(html).getString("name");

如何获取html 字符串: Make an HTTP request with android

【讨论】:

嘿...我收到此错误:puu.sh/1mF6v .. 当我使用代码时,这是什么意思? .. 我在所有示例中都有错误。 该错误表示您正在 UI 线程上运行网络操作,这在早期的 Android 版本中是不受欢迎的;从 HoneyComb 开始,它会抛出一个 RunTimeException 。 Read this.【参考方案4】:
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) 
    */

【讨论】:

【参考方案5】:

尝试:

 // 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/

【讨论】:

嗨,你知道怎么解决***.com/questions/34591855/store-php-value-to-java吗?【参考方案6】:
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);

    


【讨论】:

以上是关于从 Android 上的 URL 简单解析 JSON 并显示在列表视图中的主要内容,如果未能解决你的问题,请参考以下文章

从 Json URL 读取 Lan ,Long 并将 lat 和 long 分配给 map 的标记?

从0到1实现一个Android路由——URL解析器

如何从android中的url解析xml?

如何从 android http get 访问本地端口 8080 url

如何将图像从 url 加载到小部件的 android 远程视图中

从 Android Studio 中的 URL 解析 XML