JSON对象空的Andr​​oid的AsyncTask

JSON对象空的Andr​​oid的AsyncTask

本文介绍了JSON对象空的Andr​​oid的AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想消费REST服务,下载JSON和把它放在一个对象,然后返回它,但对象总是返回我空,这是类:

 公共类JSONParser {静态InputStream为= NULL;
静态的JSONObject jObj = NULL;
静态JSON字符串=;
上下文CTX;//构造
公共JSONParser(上下文CTX){    this.ctx = CTX;}公众的JSONObject getJSONFromUrl(字符串URL){    AsyncjSONTask任务=新AsyncjSONTask();    task.execute(URL);    返回jObj;}私有类AsyncjSONTask扩展的AsyncTask<弦乐,无效的JSONObject> {    @覆盖
    受保护的JSONObject doInBackground(字符串... PARAMS){        字符串URL =参数[0];
        InputStream为= NULL;
        //使HTTP请求
                尝试{
                    // defaultHttpClient
                    DefaultHttpClient的HttpClient =新DefaultHttpClient();
                    HttpPost httpPost =新HttpPost(URL);                    HTT presponse HTT presponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = HTT presponse.getEntity();
                    是= httpEntity.getContent();                }赶上(UnsupportedEncodingException五){
                    e.printStackTrace();
                }赶上(ClientProtocolException E){
                    e.printStackTrace();
                }赶上(IOException异常五){
                    e.printStackTrace();
                }
                JSONObject的jObjOut = NULL;
                尝试{
                    读者的BufferedReader =新的BufferedReader(新的InputStreamReader(是,ISO-8859-1),8);
                    StringBuilder的SB =新的StringBuilder();
                    串线= NULL;
                    而((行= reader.readLine())!= NULL){
                        sb.append(行+\\ n);
                    }
                    is.close();
                    JSON = sb.toString();
                }赶上(例外五){
                    Log.e(缓冲区错误,错误转换结果+ e.toString());
                }                //尝试分析字符串到一个JSON对象
                尝试{
                    jObjOut =新的JSONObject(JSON);                }赶上(JSONException E){
                    Log.e(JSON解析器,错误分析数据+ e.toString());
                }
        返回jObjOut;
    }    @覆盖
    保护无效onPostExecute(JSONObject的jObjIn){        jObj = jObjIn;
    }}}

如果有另一种方式来消费REST服务,请告诉我。


解决方案

  1. 请确保您想要做一个HTTP POST,而不是GET。

  2. 读取响应之前,它是检查什么的HTTP响应状态是一个好主意

  3. 请不要换你异步code在非异步类?看来你越来越糊涂了,把它作为如果它不是异步。

您JSONParser类是假设AsyncTask的时候,其实它是不是异步。这里是你会怎么做你正在尝试做一个例子:

 公共类MainActivity延伸活动{    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        新AsyncJsonTask(本).execute();    }    公共无效doSomethingWithTheResult(JSONObject的结果){
        //显示的查看结果,或做任何与它。
    }    私有类AsyncJsonTask扩展的AsyncTask<弦乐,无效的JSONObject> {        私人MainActivity _activity;        公共AsyncJsonTask(MainActivity活动){
            this._activity =活动;
        }        @覆盖
        受保护的JSONObject doInBackground(字符串... PARAMS){
            JSONObject的outputObject = NULL;            //调用Web服务来回报输出
            // ...            返回outputObject
        }        @覆盖
        保护无效onPostExecute(JSONObject的结果){
            _activity.doSomethingWithTheResult(结果);
        }    }
}

i want to consume a rest service, download the json and put it in a object, then return it, but the object always return me null, this is the class:

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
Context ctx;

// constructor
public JSONParser(Context ctx) {

    this.ctx = ctx;

}

public JSONObject getJSONFromUrl(String url) {

    AsyncjSONTask task = new AsyncjSONTask();

    task.execute(url);

    return jObj;

}

private class AsyncjSONTask extends AsyncTask<String, Void, JSONObject>{



    @Override
    protected JSONObject doInBackground(String... params) {

        String url = params[0];
        InputStream is = null;
        // Making HTTP request
                try {
                    // defaultHttpClient
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(url);

                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                JSONObject jObjOut = null;
                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 {
                    jObjOut = new JSONObject(json);

                } catch (JSONException e) {
                    Log.e("JSON Parser", "Error parsing data " + e.toString());
                }
        return jObjOut;
    }

    @Override
    protected void onPostExecute(JSONObject jObjIn) {

        jObj = jObjIn;
    }

}

}

if there's another way to consume rest services, please tell me.

解决方案
  1. Please make sure you want to do a HTTP POST and not a GET.
  2. Before reading the response it is a good idea to check what the HTTP Response status was
  3. Don't wrap your Async code in a non-async class? It seems you are getting confused and calling it as if its not async.

Your JSONParser class is assuming the AsyncTask is NOT Async when in fact it is. Here is an example of how you would do what you are trying to do:

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        new AsyncJsonTask(this).execute();

    }

    public void doSomethingWithTheResult(JsonObject result) {
        // Show the result on the View or do whatever with it.
    }

    private class AsyncJsonTask extends AsyncTask<String, Void, JsonObject> {

        private MainActivity _activity;

        public AsyncJsonTask(MainActivity activity) {
            this._activity = activity;
        }

        @Override
        protected JsonObject doInBackground(String... params) {
            JsonObject outputObject = null;

            // Call your web service to return the output
            // ...

            return outputObject
        }

        @Override
        protected void onPostExecute(JsonObject result) {
            _activity.doSomethingWithTheResult(result);
        }

    }
}

这篇关于JSON对象空的Andr​​oid的AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 12:49