【问题标题】:Passing JSONObject to AsyncTask then using HttpPost to send to PHP server将 JSONObject 传递给 AsyncTask,然后使用 HttpPost 发送到 PHP 服务器
【发布时间】:2012-11-13 23:36:06
【问题描述】:

经过大量研究后,我无法通过传入JSONObject 然后检索服务器端来找到使用AsyncTaskHttpPostJSONObject 的人。我正在通过多个HashMaps 填充JSONObject

当我将 JSONObject 传递给 AsyncTask 时,我得到了一个看起来像 JSONObject 的引用,我不确定如何正确解析 PHP 服务器端。


JSONObject builder 方法和AsyncTask caller:

HashMap<Integer, HashMap<String, String>> finalHash;
HashMap<String, String> semiFinalHash;
private void completeSurvey() throws JSONException {

    finalHash = new HashMap<Integer, HashMap<String, String>>();
    semiFinalHash = new HashMap<String, String>();

    JSONArray jArray = new JSONArray();
    JSONObject joMap = new JSONObject();
    for (int indexInt = 0; indexInt <= lightingMap.size(); indexInt++) {
        if (lightingMap.containsKey(indexInt) && !placeholderHashMap.containsKey(indexInt)) {
            int checkId = indexInt;
            placeholderHashMap.put(checkId, "null");
        }
    }

    Log.i("", "" + placeholderHashMap.toString());
    for (int finalOutPut = 0; finalOutPut < lightingMap.size(); finalOutPut++) {
        JSONObject jo = new JSONObject();
        try {
            int id = finalOutPut + 1;
            jo.put("id", id);
            jo.put("SurveyPhoto", placeholderHashMap.get(id));
            jo.put("Lighting", lightingMap.get(id));
            jo.put("Notes", signSpecNotesMap.get(id));
            jo.put("AdditionalService", chkBxMap.get(id));
            //jo.put("Coordinates", latLngMap.get(id));
            jArray.put(jo);

        } catch (Exception e) {
            Log.e("", "" + e.getMessage());
        }
    }
    joMap.put(businessName, jArray);
    Log.i("JSONObject", joMap.toString());
    new CompleteSurveyAsync().execute(joMap);
}

AsyncTask类:

class CompleteSurveyAsync extends AsyncTask<JSONObject, Void, String> {

    public ProgressDialog progressDialog = new ProgressDialog(Main.this);

    protected void onPreExecute() {
        progressDialog.setMessage("Submitting Data to Server...");
        progressDialog.show();
        progressDialog.setOnCancelListener(new OnCancelListener() {
            public void onCancel(DialogInterface diaInterface) {
                CompleteSurveyAsync.this.cancel(true);
                diaInterface.dismiss();
            }
        });
    }

    String inString, parameterPass;
    JSONObject jobject;
    @Override
    protected String doInBackground(JSONObject... jObject) {

        parameterPass = jObject.toString();
        Log.i("doInBackground", parameterPass);
        String url_select = "http://www.somewebsite.com/db/completedSurvey.php";
        HttpResponse response;
        try {

            HttpPost httpPost = new HttpPost(url_select);
            HttpClient httpClient = new DefaultHttpClient();

            httpPost.setEntity(new ByteArrayEntity(jObject.toString().getBytes("UTF8")));
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            response = (HttpResponse) httpClient.execute(httpPost);

            HttpEntity entity = response.getEntity();

            if(entity != null) {
                InputStream in = response.getEntity().getContent();
                inString = in.toString();
                Log.i("InputStream", "" + in.toString());
            }

        } 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();
        }
        return parameterPass;
    }

    protected void onPostExecute(String s) {
        this.progressDialog.dismiss();
        Log.i("onPostExecute", s);
        Toast.makeText(Main.this, s, Toast.LENGTH_LONG).show();
    }

}

这给了我一个 LogCat 输出:

11-13 09:52:45.606: I/JSONObject(2601): {"SOME COMPANY":[{"Notes":"null","SurveyPhoto":"[B@427a1fa8","id":1,"Lighting":1,"AdditionalService":0},{"Notes":"null","SurveyPhoto":"null","id":2,"Lighting":0,"AdditionalService":0},{"Notes":"null","SurveyPhoto":"null","id":3,"Lighting":1,"AdditionalService":0},{"Notes":"null","SurveyPhoto":"null","id":4,"Lighting":1,"AdditionalService":0}]}
11-13 09:52:45.626: I/doInBackground(2601): [Lorg.json.JSONObject;@416ad478
11-13 09:52:45.786: I/InputStream(2601): org.apache.http.conn.EofSensorInputStream@416c51d0
11-13 09:52:45.816: I/onPostExecute(2601): [Lorg.json.JSONObject;@416ad478

我验证了JSON,构建它工作正常,但是当通过AsyncTask 我开始得到[Lorg.json.JSONObject;@4158c990,这是一个对象引用吗?如果是这样,我该如何解析这个 PHP 服务器端?

我当前的 PHP 设置为只写入文件:

$json = file_get_contents('php://input');
$jsonObj = json_decode($json, true);

$jsonFile = "json.txt";
$fh = fopen($jsonFile, 'a');

fwrite($fh, $json);
fwrite($fh, "\n");
fwrite($fh, $jsonObj);
fwrite($fh, "\n");

fclose($fh);

输出(json.txt):

[Lorg.json.JSONObject;@416ad478

【问题讨论】:

    标签: android android-asynctask json


    【解决方案1】:

    JSONObject... jObject 表示jObject 不是JSONObject ...它是一个可变参数/数组

    试试

    if(jObject.length > 0)
    {
      final JSONObject realjObject = jObject[0];
      //rest of code goes here and instead of jObject we are using realjObject
    }
    

    编辑: 而是:

    httpPost.setEntity(new ByteArrayEntity(jObject.toString().getBytes("UTF8")));
    

    使用(仅用于干净的代码:)):

    httpPost.setEntity(new StringEntity(jObject.toString(), "UTF8"));
    

    【讨论】:

    • 先生,您是救生员,非常感谢。希望我能再+1一次。曾几何时,我知道,应该退后一步,真正考虑一下物体是如何通过的。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    • 2015-06-20
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多