从Android的URL简单解析JSON简单、Android、URL、JSON

2023-09-11 20:33:11 作者:傻逼年年有,今年特别多

我试图解析JSON结果从我的Andr​​oid应用程序的URL牵强......我试图在互联网上的几个例子,但不能让它的工作。

JSON数据如下: {活动:1,名:testtest,tab1_text:测试选项卡} ...(有效)

什么是获取URL和解析JSON数据和前最简单的方法。只显示它在日志中像...

  response.getString(姓名);
 

解决方案

您可以使用的AsyncTask ,你必须定制,以满足您的需求,但类似的以下

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

在preExecute() - 最常用于建立和启动一个进程对话框

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

onPostExecute() - 在这里,我们已经走出了后台线程的,所以我们能做的用户界面,操控响应数据,或者干脆指定响应特定的变量类型

首先,我们将开始类,初始化字符串持有的方法之外,但在类中的结果,然后在$运行 p $ pExecute()方法建立一个简单的进度对话框。

 类MyAsyncTask扩展的AsyncTask<字符串,字符串,太虚> {

    私人ProgressDialog progressDialog =新ProgressDialog(MainActivity.this);
    的InputStream的InputStream = NULL;
    字符串结果=;

    在preExecute保护无效(){
        progressDialog.setMessage(下载你的数据......);
        progressDialog.show();
        progressDialog.setOnCancelListener(新OnCancelListener(){
            公共无效OnCancel的(DialogInterface为arg0){
                MyAsyncTask.this.cancel(真正的);
            }
        });
    }
 
Android okhttp JSON数据并解析 一

接着我们需要建立连接,我们要如何处理响应:

  @覆盖
    保护无效doInBackground(字符串... PARAMS){

        字符串url_select =htt​​p://yoururlhere.com;

        ArrayList的<的NameValuePair>参数=新的ArrayList<的NameValuePair>();

        尝试 {
            //设置HTTP发布

            // HttpClient的是更多的则更少去precated。需要改变的URLConnection
            HttpClient的HttpClient的=新DefaultHttpClient();

            HttpPost httpPost =新HttpPost(url_select);
            httpPost.setEntity(新UrlEn codedFormEntity(参数));
            HTT presponse HTT presponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = HTT presponse.getEntity();

            //读取内容和放大器;登陆
            的InputStream = httpEntity.getContent();
        }赶上(UnsupportedEncodingException E1){
            Log.e(UnsupportedEncodingException,e1.toString());
            e1.printStackTrace();
        }赶上(ClientProtocolException E2){
            Log.e(ClientProtocolException,e2.toString());
            e2.printStackTrace();
        }赶上(IllegalStateException异常E3){
            Log.e(IllegalStateException异常,e3.toString());
            e3.printStackTrace();
        }赶上(IOException异常E4){
            Log.e(IOException异常,e4.toString());
            e4.printStackTrace();
        }
        //将使用字符串构建器响应字符串
        尝试 {
            的BufferedReader面包屑=新的BufferedReader(新的InputStreamReader(InputStream中,UTF-8),8);
            StringBuilder的sBuilder =新的StringBuilder();

            串线= NULL;
            而((行= bReader.readLine())!= NULL){
                sBuilder.append(行+\ N);
            }

            inputStream.close();
            结果= sBuilder.toString();

        }赶上(例外五){
            Log.e(StringBuilding和放大器; BufferedReader类,错误将导致+ e.toString());
        }
    } //保护无效doInBackground(字符串... PARAMS)
 

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

 保护无效onPostExecute(空V){
        //解析JSON数据
        尝试 {
            JSONArray jArray =新JSONArray(结果);
            对于(i = 0; I< jArray.length();我++){

                的JSONObject jObject = jArray.getJSONObject(ⅰ);

                字符串名称= jObject.getString(姓名);
                串tab1_text = jObject.getString(tab1_text);
                INT有效= jObject.getInt(激活);

            } //结束循环
            this.progressDialog.dismiss();
        }赶上(JSONException E){
            Log.e(JSONException,错误:+ e.toString());
        } //赶上(JSONException E)
    } //保护无效onPostExecute(虚空V)
} //类MyAsyncTask扩展的AsyncTask<字符串,字符串,太虚>
 

I'm trying to parse a JSON result fetched from a URL in my Android app ... I have tried a few examples on the Internet, but can't get it to work.

The JSON data looks like this: {"active":1,"name":"testtest","tab1_text":"Test TAB"} ... ( is valid )

What's the simplest way to fetch the URL and parse the JSON data and ex. just show it in the log like...

response.getString("name");

解决方案

You could use AsyncTask, you'll have to customize to fit your needs, but something like the following

Async task has three primary methods:

onPreExecute() - most commonly used for setting up and starting a progress dialog

doInBackground() - Makes connections and receives responses from the server (Do NOT try to assign response values to GUI elements, this is a common mistake, that cannot be done in a background thread).

onPostExecute() - Here we are out of the background thread, so we can do user interface manipulation with the response data, or simply assign the response to specific variable types.

First we will start the class, initialize a String to hold the results outside of the methods but inside the class, then run the onPreExecute() method setting up a simple progress dialog.

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);
            }
        });
    }

Then we need to set up the connection and how we want to handle the response:

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

Lastly, here we will parse the return, in this example it was a JSON Array and then dismiss the dialog:

    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>