android json解析没有tag的值

时间:2014-10-13 04:49:37

标签: android json parsing

我需要使用以下代码解析JSON

    urlGetDeviceIdMobileNo = Global.URL + "device_id="
                    + strDeviceIdLocal;

public class GetDeviceId extends AsyncTask<Void, Void, Void> {
        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            progressDialog = new ProgressDialog(LoginScreen.this);
            progressDialog.setMessage("Please Wait...");
            progressDialog.setCancelable(false);
            progressDialog.show();
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            JSONParser jParser = new JSONParser();
            JSONObject json = jParser.getJSONFromUrl(urlGetDeviceIdMobileNo);
            System.out.println("!!!!!!!!!!!! json==="+json);

            try {

                strDeviceIdServer = (String) json.getString(TAG_DEVICE_ID);
                strMobileNoServer = (String) json.getString(TAG_MOBILE_NO);

            } catch (JSONException e) {
                e.printStackTrace();
            }
return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
}

我的Json数据是:

{
   status: "success",
   data: 
   {
      device_id: "35xxxxxxcccccvvvv",
      mobile_number: "955896xxxxx"
   }
}

但是logcat说:

  org.json.JSONException: No value for device_id

2 个答案:

答案 0 :(得分:2)

只需替换此

try {

                strDeviceIdServer = (String) json.getString(TAG_DEVICE_ID);
                strMobileNoServer = (String) json.getString(TAG_MOBILE_NO);

            } catch (JSONException e) {
                e.printStackTrace();
            }

使用

try {

            strDeviceIdServer = json.getJSONObject("data").getString(TAG_DEVICE_ID);
            strMobileNoServer = json.getJSONObject("data").getString(TAG_MOBILE_NO);

        } catch (JSONException e) {
            e.printStackTrace();
        }

答案 1 :(得分:2)

您的解析不正确。您的JSONObject具有子JSONObject&#34; data&#34;,并且此子JSONObject包含device_id。因此,您必须解析它:

try {
        JSONObject childJson = json.getJSONObject("data");
        if(childJson.has(TAG_DEVICE_ID))
            strDeviceIdServer = childJson.getString(TAG_DEVICE_ID);
        if(childJson.has(TAG_MOBILE_NO))
            strMobileNoServer = childJson.getString(TAG_MOBILE_NO);
    } catch (JSONException e) {
        e.printStackTrace();
    }