簡體   English   中英

java.lang.String無法轉換為JSONObject

[英]java.lang.String cannot be converted to JSONObject

我正在嘗試解析從服務器收到的JSON以下

{"status":1,"data":{"msg":"Invertory Added","inventory_id":2001}}

在下面使用

try 
{
    jObj = new JSONObject(json);
    final Integer status = jObj.getInt("status");

    if(status == 1) {
        msg="Inventory Created Successfully";
    } else { 
        msg = jObj.getString("data"); 
    }

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    builder.setTitle("Info")
        .setMessage(msg)
        .setCancelable(false)
        .setIcon(R.drawable.ic_launcher)
        .setPositiveButton("OK", 
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    //do things
                    if(status==1)
                    {
                        displayView(6);
                    }
                }
            });

    AlertDialog alert = builder.create();
    alert.show();

} catch (JSONException e) {
    Log.e("msgtest", "unexpected JSON exception", e);
    // Do something to recover ... or kill the app.
}

日志說

E/msgtest﹕ unexpected JSON exception

org.json.JSONException: Value org.apache.http.conn.BasicManagedEntity@41f14cd0 of type java.lang.String cannot be converted to JSONObject
    at org.json.JSON.typeMismatch(JSON.java:111)
    at org.json.JSONObject.<init>(JSONObject.java:158)
    at org.json.JSONObject.<init>(JSONObject.java:171)
    at info.androidhive.wolf.NewInventoryFragment$submitAction.onPostExecute(NewInventoryFragment.java:575)
    at info.androidhive.wolf.NewInventoryFragment$submitAction.onPostExecute(NewInventoryFragment.java:388)

在第575行jObj = new JSONObject(json);


的AsyncTask

@Override
protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(getActivity());
    pDialog.setMessage("Loading");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    pDialog.show();
}

@Override
protected String doInBackground(String... arg0) {
    // TODO Auto-generated method stub
    File file1 = new File(selectedPath1);
    File file2 = new File(selectedPath2);
    File file3 = new File(selectedPath3);
    File file4 = new File(selectedPath4);
    File file5 = new File(selectedPath5);
    String urlString="http://url/index.php";

    List<NameValuePair> params = new ArrayList<NameValuePair>();

    try
    {
        FileBody bin2 = new FileBody(file2);
        FileBody bin3 = new FileBody(file3);
        FileBody bin4 = new FileBody(file4);
        FileBody bin5 = new FileBody(file5);

        params.add(new BasicNameValuePair("section","inventory"));
        params.add(new BasicNameValuePair("action","new"));
        params.add(new BasicNameValuePair("apron_id",stock_number_ele.getText().toString()));
        params.add(new BasicNameValuePair("nickname",nick_name_ele.getText().toString()));
        params.add(new BasicNameValuePair("location",location));
        params.add(new BasicNameValuePair("manufacture",manufacture));
        params.add(new BasicNameValuePair("core_material",core_material_ele.getText().toString()));
        params.add(new BasicNameValuePair("color",color_ele.getText().toString()));
        params.add(new BasicNameValuePair("Date_purchase",dop_ele.getText().toString()));
        params.add(new BasicNameValuePair("UID_no",gtin_uid_ele.getText().toString()));
        params.add(new BasicNameValuePair("serial",serial_ele.getText().toString()));
        params.add(new BasicNameValuePair("Batch",batch_lot_ele.getText().toString()));
        params.add(new BasicNameValuePair("Expiration",ed_ele.getText().toString()));
        params.add(new BasicNameValuePair("garment_type",description_ele.getText().toString()));
        params.add(new BasicNameValuePair("QTY",county_ele.getText().toString()));
        params.add(new BasicNameValuePair("user_id",SignInActivity.user_id));*/

        HttpClient client = new DefaultHttpClient();

        HttpPost post = new HttpPost(urlString);

        FileBody bin1 = new FileBody(file1);
        FileBody bin2 = new FileBody(file2);
        FileBody bin3 = new FileBody(file3);
        FileBody bin4 = new FileBody(file4);
        FileBody bin5 = new FileBody(file5);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("section", new StringBody("inventory"));
        reqEntity.addPart("action", new StringBody("new"));
        reqEntity.addPart("apron_id", new StringBody(stock_number_ele.getText().toString()));
        reqEntity.addPart("nickname", new StringBody(nick_name_ele.getText().toString()));
        reqEntity.addPart("location", new StringBody(location+""));
        reqEntity.addPart("manufacture", new StringBody(manufacture+""));
        reqEntity.addPart("core_material", new StringBody(core_material_ele.getText().toString()));
        reqEntity.addPart("color", new StringBody(color_ele.getText().toString()));
        reqEntity.addPart("Date_purchase", new StringBody(dop_ele.getText().toString()));
        reqEntity.addPart("UID_no", new StringBody(gtin_uid_ele.getText().toString()));
        reqEntity.addPart("serial", new StringBody(serial_ele.getText().toString()));
        reqEntity.addPart("Batch", new StringBody(batch_lot_ele.getText().toString()));
        reqEntity.addPart("Expiration", new StringBody(ed_ele.getText().toString()));
        reqEntity.addPart("garment_type", new StringBody(description_ele.getText().toString()));
        reqEntity.addPart("QTY", new StringBody(county_ele.getText().toString()));
        reqEntity.addPart("user_id", new StringBody(SignInActivity.user_id));

        if(selectedPath1!="NONE")
            reqEntity.addPart("image1", bin1);

        if(selectedPath2!="NONE") {
            Log.d("Image2","Image2");
            reqEntity.addPart("image2", bin2);
        }

        if(selectedPath3!="NONE") {
            Log.d("Image3","Image2");
            reqEntity.addPart("image3", bin3);
        }

        if(selectedPath4!="NONE") {
            Log.d("Image4","Image2");
            reqEntity.addPart("image4", bin4);
        }

        if(selectedPath5!="NONE") {
            Log.d("Image5","Image2");
            reqEntity.addPart("image5", bin5);
        }

        post.setEntity(reqEntity);
        HttpResponse response = client.execute(post);
        resEntity = response.getEntity();
        final String response_str = EntityUtils.toString(resEntity);

        if (resEntity != null) {
            Log.i("RESPONSE",response_str);
        }
    }
    catch (Exception ex)
    {
        Log.e("Debug", "error: " + ex.getMessage(), ex);
    }

    return resEntity.toString();
}

@SuppressWarnings("deprecation")
//@Override
protected void onPostExecute(String json) {

    String msg="";
    JSONArray jArray=null;

    if (pDialog.isShowing()) {
        pDialog.dismiss();
    }

    try 
    {
        jObj = new JSONObject(json);
        final Integer status = jObj.getInt("status");
        msg = jObj.getString("data"); // get the name from data.

        if (status == 1) {
            msg="Inventory Created Successfully";
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        builder.setTitle("Info")
            .setMessage(msg)
            .setCancelable(false)
            .setIcon(R.drawable.ic_launcher)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    if(status==1)
                    {
                        displayView(6);
                    }
                }
            });

            AlertDialog alert = builder.create();
            alert.show();

    }
    catch (JSONException e) 
    {
        Log.e("msgtest", "unexpected JSON exception", e);
        // Do something to recover ... or kill the app.
    }
}

請提出您的意見。 提前致謝。

您正確使用EntityUtils.toString來讀取實體的內容並作為String,但是您在doInBackground中返回了錯誤的對象。 而不是返回resEntity.toString(); ,您必須返回response_str

我想我知道為什么這段代碼失敗了。

在您的代碼中,您有:

try 
{
    jObj = new JSONObject(json);
    final Integer status = jObj.getInt("status");

    if(status == 1)
    {
        msg = "Inventory Created Successfully";
    }
    else
    { 
        msg = jObj.getString("data"); 
    }

    ...

} 
catch (JSONException e) 
{
    Log.e("msgtest", "unexpected JSON exception", e);
    // Do something to recover ... or kill the app.
}

您說您正在接收這樣的JSON消息(我添加了字段的類型):

// "Main" Object
{
    "status": 1,  // Integer
    "data":       // Object
    {
        "msg" : "Invertory Added", // String
        "inventory_id" : 2001      // Integer
    }
}

因此,在您嘗試的代碼中,此msg = jObj.getString("data"); 您在JSON消息中詢問字符串 BUT,“數據”的類型為“ 對象” ,這就是為什么出現此錯誤的原因。

因此,您應該這樣做:

try 
{
    jObj = new JSONObject(json);
    final Integer status = jObj.getInt("status");

    if(status == 1) 
    {
        msg = "Inventory Created Successfully";
    }
    else
    { 
        // Here is the change
        // you should also change the type of msg to JSONObject
        // and probably the name of the variable for a better understanding 
        msg = jObj.getObject("data"); 
    }

    // And of course handle this object accordingly
    // Example : String message = msg.getString("msg");

    ...

} 
catch (JSONException e) 
{
    Log.e("msgtest", "unexpected JSON exception", e);
    // Do something to recover ... or kill the app.
}

如果我猜對了,您想檢索“數據”對象內的“ msg”字段。 您可以像這樣簡單地獲取它:

字符串消息= jObj.getObject(“ data”)。getString(“ msg”);

希望這可以幫助,

干杯。


[英]Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM