JSON解析错误:JSON数组无值

时间:2018-08-23 04:51:03

标签: android json

我有一个代码,我应该传递一个静态用户ID进行身份验证,然后从URL获取JSON响应并将其显示在listview中。但是我得到一个错误,指出“ JSON解析错误:(JSON数组)中没有值”。请帮助

  

MainActivity.java:

 public class MainActivity extends AppCompatActivity {

        private String TAG = MainActivity.class.getSimpleName();

        private ProgressDialog pDialog;
        private ListView lv;

        // URL to get contacts JSON
        private static String url = "url";

        ArrayList<HashMap<String, String>> contactList;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            contactList = new ArrayList<>();

            lv = (ListView) findViewById(R.id.list);

            new GetContacts().execute();
        }

        /**
         * Async task class to get json by making HTTP call
         */
        private class GetContacts extends AsyncTask<Void, Void, Void> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Showing progress dialog
                pDialog = new ProgressDialog(MainActivity.this);
                pDialog.setMessage("Please wait...");
                pDialog.setCancelable(false);
                pDialog.show();

            }

            @Override
            protected Void doInBackground(Void... arg0) {


     List<NameValuePair> list=new ArrayList<>();
                list.add(new BasicNameValuePair("user_id", "2"));

                HttpHandler sh = new HttpHandler();



                // Making a request to url and getting response
                String jsonStr = sh.makeServiceCall(url);

                Log.e(TAG, "Response from url: " + jsonStr);

                if (jsonStr != null) {
                    try {
                        JSONObject jsonObj = new JSONObject(jsonStr);

                        // Getting JSON Array node
                        JSONArray contacts = jsonObj.getJSONArray("promotion_lists");

                        // looping through All Contacts
                        for (int i = 0; i < contacts.length(); i++) {
                            JSONObject c = contacts.getJSONObject(i);

                            String promotion_id = c.getString("promotion_id");
                            String promotion_title = c.getString("promotion_title");
                            String promotion_description = c.getString("promotion_description");
    //
                            HashMap<String, String> contact = new HashMap<>();

                            // adding each child node to HashMap key => value
                            contact.put("promotion_id", promotion_id);
                            contact.put("promotion_title", promotion_title);
                            contact.put("promotion_description", promotion_description);

                            // adding contact to contact list
                            contactList.add(contact);
                        }
                    } catch (final JSONException e) {
                        Log.e(TAG, "Json parsing error: " + e.getMessage());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(),
                                        "Json parsing error: " + e.getMessage(),
                                        Toast.LENGTH_LONG)
                                        .show();
                            }
                        });

                    }
                } else {
                    Log.e(TAG, "Couldn't get json from server.");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Couldn't get json from server. Check LogCat for possible errors!",
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }

                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                Log.e("SignUpRsp", String.valueOf(result));

                // Dismiss the progress dialog
                if (pDialog.isShowing())
                    pDialog.dismiss();
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        MainActivity.this, contactList,
                        R.layout.list_item, new String[]{"promotion_id", "promotion_title",
                        "promotion_description"}, new int[]{R.id.promotion_id,
                        R.id.promotion_title, R.id.promotion_desc});

                lv.setAdapter(adapter);
            }


        }
        public String PostData(String[] valuse) {
            String s="";


            try
            {
                HttpClient httpClient=new DefaultHttpClient();
                HttpPost httpPost=new HttpPost("url");

                List<NameValuePair> list=new ArrayList<>();
                list.add(new BasicNameValuePair("user_id", "value"));


                httpPost.setEntity(new UrlEncodedFormEntity(list));
                HttpResponse httpResponse=  httpClient.execute(httpPost);

                HttpEntity httpEntity=httpResponse.getEntity();
                s= readResponse(httpResponse);

            }
            catch(Exception exception)  {}
            return s;


        }
        public String readResponse(HttpResponse res) {
            InputStream is=null;
            String return_text="";
            try {
                is=res.getEntity().getContent();
                BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
                String line="";
                StringBuffer sb=new StringBuffer();
                while ((line=bufferedReader.readLine())!=null)
                {
                    sb.append(line);
                }
                return_text=sb.toString();
            } catch (Exception e)
            {

            }
            return return_text;

        }
    } 
  

JSON响应:

  {
            "status": "1",
            "message": "Ok",
            "promotion_lists": [
                {
                    "promotion_id": "3",
                    "promotion_image_name": "1.jpg",
                    "promotion_image_url": "url.jpg",
                    "promotion_title": "winner",
                    "promotion_description": "good\ngold\nred",
                    "admin_status": "1",
                    "promotion_status": "1",
                    "promotion_status_description": "Live"
                },

            ]
        } 

5 个答案:

答案 0 :(得分:1)

您的json也有问题,您可以尝试使用此输出json吗?不需要数组中的最后一个逗号。

{
        "status": "1",
        "message": "Ok",
        "promotion_lists": [
            {
                "promotion_id": "3",
                "promotion_image_name": "1.jpg",
                "promotion_image_url": "url.jpg",
                "promotion_title": "winner",
                "promotion_description": "good\ngold\nred",
                "admin_status": "1",
                "promotion_status": "1",
                "promotion_status_description": "Live"
            }
        ]
}

答案 1 :(得分:1)

您的JSON解析正确

如果您的响应状态响应代码为1,则需要解析JSON

示例代码

尝试一下

    if (jsonStr != null) {
        try {
            JSONObject jsonObj = new JSONObject(jsonStr);



            // check here of your status of response 
            // is status is 0 USER NOT FOUND
            if(jsonObj.getString("status").equals("0")){

           MainActivity.this.runOnUiThread(new Runnable() {
               @Override
              public void run() {
            Toast.makeText(MainActivity.this, jsonObj.getString("message"), Toast.LENGTH_SHORT).show();
               }
           });



            // is status is 1 PARSE YOUR JSON
            }else {
                JSONArray contacts = jsonObj.getJSONArray("promotion_lists");

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    String promotion_id = c.getString("promotion_id");
                    String promotion_title = c.getString("promotion_title");
                    String promotion_description = c.getString("promotion_description");

                    HashMap<String, String> contact = new HashMap<>();

                    // adding each child node to HashMap key => value
                    contact.put("promotion_id", promotion_id);
                    contact.put("promotion_title", promotion_title);
                    contact.put("promotion_description", promotion_description);

                    // adding contact to contact list
                    contactList.add(contact);
                }
            }

        } catch (final JSONException e) {
            Log.e(TAG, "Json parsing error: " + e.getMessage());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Json parsing error: " + e.getMessage(),
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }
}

答案 2 :(得分:1)

您可以使用此解决方案

public class GetContacts extends AsyncTask<String, Void, String> {
        protected void onPreExecute() {
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected String doInBackground(String... arg0) {

            try {
                URL url = new URL(URL HERE);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                conn.setRequestProperty("Accept", "application/json");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setReadTimeout(5000);
                conn.setConnectTimeout(5000);
                JSONObject postDataParams = new JSONObject();
                postDataParams.put("user_id", user_id);
                Log.i("JSON", postDataParams.toString());
                DataOutputStream os = new DataOutputStream(conn.getOutputStream());
                //os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
                os.writeBytes(postDataParams.toString());
                os.flush();
                os.close();

                Log.i("STATUS", String.valueOf(conn.getResponseCode()));
                Log.i("MSG", conn.getResponseMessage());


                int responseCode = conn.getResponseCode();

                if (responseCode == HttpsURLConnection.HTTP_OK) {

                    BufferedReader in = new BufferedReader(new
                            InputStreamReader(
                            conn.getInputStream()));

                    StringBuffer sb = new StringBuffer("");
                    String line = "";

                    while ((line = in.readLine()) != null) {

                        sb.append(line);
                        break;
                    }

                    in.close();
                    conn.disconnect();
                    return sb.toString();

                } else {
                    conn.disconnect();
                    return new String("false : " + responseCode);
                }

            } catch (Exception e) {
                return new String("Exception: " + e.getMessage());
            }

        }

        @Override
        protected void onPostExecute(String jsonStr) {
            try {
                 pDialog();
                Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray contacts = jsonObj.getJSONArray("promotion_lists");

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        String promotion_id = c.getString("promotion_id");
                        String promotion_title = c.getString("promotion_title");
                        String promotion_description = c.getString("promotion_description");
//
                        HashMap<String, String> contact = new HashMap<>();

                        // adding each child node to HashMap key => value
                        contact.put("promotion_id", promotion_id);
                        contact.put("promotion_title", promotion_title);
                        contact.put("promotion_description", promotion_description);

                        // adding contact to contact list
                        contactList.add(contact);
                    }
/**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, contactList,
                    R.layout.list_item, new String[]{"promotion_id", "promotion_title",
                    "promotion_description"}, new int[]{R.id.promotion_id,
                    R.id.promotion_title, R.id.promotion_desc});

            lv.setAdapter(adapter);

                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();

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


        }
    }
  

您不需要在 Asynctask 中使用 runOnUiThread 的另一件事,因为   两者都是 helper线程,它们用于更新UI,您不必   在其中使用 runOnUIThread ,只是简单地显示吐司,而不使用它   将显示它,阅读文档   https://developer.android.com/guide/components/processes-and-threads

答案 3 :(得分:1)

JSONArray引发错误,因为promotion_lists带有项目,但逗号不必要。

{
    "status": "1",
    "message": "Ok",
    "promotion_lists": [
        {
            "promotion_id": "3",
            "promotion_image_name": "1.jpg",
            "promotion_image_url": "url.jpg",
            "promotion_title": "winner",
            "promotion_description": "good\ngold\nred",
            "admin_status": "1",
            "promotion_status": "1",
            "promotion_status_description": "Live"
        }
    ]
} 

答案 4 :(得分:1)

您的JSON解析看起来不错。问题出在您的JSON响应上。这不是有效的JSON响应,因为JSON数组“ promotion_lists”之后有不必要的逗号。尝试删除逗号。