java.lang.String无法转换为JSONObject

时间:2015-05-04 14:04:01

标签: java android json

我正在尝试解析从服务器

收到的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.
    }
}

请提出您的意见。提前致谢。

2 个答案:

答案 0 :(得分:1)

您正确使用EntityUtils.toString来读取实体的内容并作为String,但是您在doInBackground中返回了错误的对象。您必须返回resEntity.toString();

,而不是返回response_str

答案 1 :(得分:0)

我想我知道为什么这段代码失败了。

你的代码中有

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消息中询问字符串但是“数据”的类型为对象,这就是为什么你得到这个错误。

所以你应该这样做:

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.
}

如果我猜对了,你想要检索“data”对象中的“msg”字段。你可以这样简单地得到它:

  

String message = jObj.getObject(“data”)。getString(“msg”);

希望这有帮助,

干杯。