2015-05-04 6 views
0

Я пытаюсь разобрать ниже JSON, который получен от сервераjava.lang.String не могут быть преобразованы в JSONObject

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

Log говорит

E/msgtest﹕ unexpected JSON exception 

org.json.JSONException: Value [email protected] 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. 
    } 
} 

Пожалуйста, укажите Ваше мнение. Заранее спасибо.

+0

Опубликовать весь AsyncTask – Blackbelt

+0

, который можно вставить. Недостаточно ли этого получить @Blackbelt –

+0

нет. Строка, которую вы опубликовали, является действительным json. Таким образом, вы, вероятно, возитесь где-то в другом месте. Может не весь AsyncTask .. Как вы преобразовываете входной поток в строку? – Blackbelt

ответ

1

Вы правильно используете EntityUtils.toString, чтобы прочитать содержимое объекта и как строку, но вы возвращаете неправильный объект в doInBackground. Вместо того, чтобы возвращать resEntity.toString();, вы должны вернуть response_str.

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"); вы спрашиваете String НО, но в вашем сообщении 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. 
} 

Если я угадал правильно, вы хотели, чтобы получить поле «сообщение» внутри «данных» объекта. Вы можете просто получить его так:

String message = jObj.getObject ("data"). GetString ("msg");

Надеется, что это помогает,

Приветствие.

Смежные вопросы