json.JSONException:没有ProductList的值

时间:2016-03-22 05:07:02

标签: android json

以下是从项目列表中搜索的代码。但是它给出了json.JSONException:每次都没有ProductList错误的值并打印"无法连接服务器请稍后再试"。

来自Search.java的

myAsyncTask类

 class myAsyncTask extends AsyncTask<String, Void, String>{

    JSONParser jParser;
    JSONArray productList;
    String url = new String();
    String textSearch;
    ProgressDialog pd;

    @Override
    protected void onPreExecute(){

        super.onPreExecute();
        productList = new JSONArray();
        jParser = new JSONParser();
        pd = new ProgressDialog(getActivity());
        pd.setCancelable(false);
        pd.setMessage("Searching....");
        pd.getWindow().setGravity(Gravity.CENTER);
        pd.show();

    }

    @Override
    protected String doInBackground(String... sText){

        url= "http://demo5657559.mockable.io/getitems"+sText[0];
        String returnResult = getProductList(url);
        this.textSearch = sText[0];
        return returnResult;


    }

    public String getProductList(String url){

        Product tempProduct = new Product();
        String matchFound = "N";
        Log.d("Tatheer", "productResults size - "+productResults.size());

        try{

            JSONObject json = jParser.getJSONFromUrl(url);
            productList = json.getJSONArray("ProductList");

            for(int i = 0; i<productList.length();i++){

                tempProduct = new Product();

                JSONObject obj = productList.getJSONObject(i);


                tempProduct.setProductCode(obj.getString("ProductCode"));
                tempProduct.setProductName(obj.getString("ProductName"));
                tempProduct.setProductGrammage(obj.getString("ProductGrammage"));
                tempProduct.setProductBarcode(obj.getString("ProductBarcode"));
                tempProduct.setProductDivision(obj.getString("ProductCatCode"));
                tempProduct.setProductDepartment(obj.getString("ProductSubCode"));
                tempProduct.setProductMRP(obj.getString("ProductMRP"));
                tempProduct.setProductBBPrice(obj.getString("ProductBBPrice"));

                matchFound = "N";

                for (int j = 0; j < productResults.size();j++){

                    if (productResults.get(j).getProductCode().equals(tempProduct.getProductCode())){

                        matchFound = "Y";
                    }

                }

                if (matchFound == "N"){

                    productResults.add(tempProduct);

                }



            }

            Log.d("Tatheer", "productResults size - "+productResults.size());
            return ("OK");



        }

        catch (Exception e){

            e.printStackTrace();
            return ("Exception Caught");
        }

    }

    @Override
    protected void onPostExecute(String result){

        super.onPostExecute(result);
        if (result.equalsIgnoreCase("Exception Caught")){

            Toast.makeText(getActivity(), "Unable to connect Server please try later", Toast.LENGTH_LONG).show();

            pd.dismiss();

        }

        else {


            Log.d("Tatheer", "existing on PostExecute");
            filterProductArray(textSearch);
            searchResults.setAdapter(new SearchResultsAdapter(getActivity(), filteredProductResults));
            pd.dismiss();
        }

    }


}


}

logcat的:

03-22 09:50:56.624 5733-5764/? W/System.err: org.json.JSONException: No                    value for ProductList
03-22 09:50:56.624 5733-5764/? W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
03-22 09:50:56.624 5733-5764/? W/System.err:     at org.json.JSONObject.getJSONArray(JSONObject.java:584)
03-22 09:50:56.624 5733-5764/? W/System.err:     at com.zing.basket.Search$myAsyncTask.getProductList(Search.java:167)
03-22 09:50:56.624 5733-5764/? W/System.err:     at com.zing.basket.Search$myAsyncTask.doInBackground(Search.java:151)
03-22 09:50:56.624 5733-5764/? W/System.err:     at com.zing.basket.Search$myAsyncTask.doInBackground(Search.java:125)
03-22 09:50:56.624 5733-5764/? W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
03-22 09:50:56.625 5733-5764/? W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-22 09:50:56.625 5733-5764/? W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
03-22 09:50:56.625 5733-5764/? W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
03-22 09:50:56.625 5733-5764/? W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
03-22 09:50:56.625 5733-5764/? W/System.err:     at java.lang.Thread.run(Thread.java:818)
03-22 09:50:56.741 5733-5748/? E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab3d3650

的Json

{
"ProductList":[
{

"ProductCode":"1", 
"ProductName":"DALDA Cooking oil 1 LTR",
"ProductGrammage":"5g",
"ProductBarcode":"1234567891011",
"ProductCatCode":"EDIBLE GROCERY",
"ProductSubCode":"OIL/GHEE",
"ProductMRP":"100",
"ProductBBPrice": "120"

}
]}

请帮忙!

3 个答案:

答案 0 :(得分:0)

url =“http://demo5657559.mockable.io/getitems”+ sText [0];

我认为你需要在URL中使用反斜杠。 向API开发人员询问调用web api的正确格式,并尝试使用url =“http://demo5657559.mockable.io/getitems/”+ sText [0];

请注意网址中添加的反斜杠。

如果网址不正确,您可能会收到端点未找到错误,并且响应中不会出现JSONArray“ProductList”。

答案 1 :(得分:0)

class myAsyncTask extends AsyncTask<String, Void, String>{

    JSONParser jParser;
    JSONArray productList;
    String url = new String();
    String textSearch;
    ProgressDialog pd;
    String sText[0]=null;

    @Override
    protected void onPreExecute(){

        super.onPreExecute();
        productList = new JSONArray();
        jParser = new JSONParser();
        pd = new ProgressDialog(getActivity());
        pd.setCancelable(false);
        pd.setMessage("Searching....");
        pd.getWindow().setGravity(Gravity.CENTER);
        pd.show();

    }

    @Override
    protected String doInBackground(String... sText){
if(sText[0]!=null){
        url= "http://demo5657559.mockable.io/getitems"+sText[0];
        String returnResult = getProductList(url);
        this.textSearch = sText[0];
        return returnResult;
}else{
url= "http://demo5657559.mockable.io/getitems";
            String returnResult = getProductList(url);
            this.textSearch = sText[0];
            return returnResult;
}



    }

    public String getProductList(String url){

        Product tempProduct = new Product();
        String matchFound = "N";
        Log.d("Tatheer", "productResults size - "+productResults.size());

        try{

            JSONObject json = jParser.getJSONFromUrl(url);
            productList = json.getJSONArray("ProductList");

            for(int i = 0; i<productList.length();i++){

                tempProduct = new Product();

                JSONObject obj = productList.getJSONObject(i);


                tempProduct.setProductCode(obj.getString("ProductCode"));
                tempProduct.setProductName(obj.getString("ProductName"));
                tempProduct.setProductGrammage(obj.getString("ProductGrammage"));
                tempProduct.setProductBarcode(obj.getString("ProductBarcode"));
                tempProduct.setProductDivision(obj.getString("ProductCatCode"));
                tempProduct.setProductDepartment(obj.getString("ProductSubCode"));
                tempProduct.setProductMRP(obj.getString("ProductMRP"));
                tempProduct.setProductBBPrice(obj.getString("ProductBBPrice"));

                matchFound = "N";

                for (int j = 0; j < productResults.size();j++){

                    if (productResults.get(j).getProductCode().equals(tempProduct.getProductCode())){

                        matchFound = "Y";
                    }

                }

                if (matchFound == "N"){

                    productResults.add(tempProduct);

                }



            }

            Log.d("Tatheer", "productResults size - "+productResults.size());
            return ("OK");



        }

        catch (Exception e){

            e.printStackTrace();
            return ("Exception Caught");
        }

    }

    @Override
    protected void onPostExecute(String result){

        super.onPostExecute(result);
        if (result.equalsIgnoreCase("Exception Caught")){

            Toast.makeText(getActivity(), "Unable to connect Server please try later", Toast.LENGTH_LONG).show();

            pd.dismiss();

        }

        else {


            Log.d("Tatheer", "existing on PostExecute");
            filterProductArray(textSearch);
            searchResults.setAdapter(new SearchResultsAdapter(getActivity(), filteredProductResults));
            pd.dismiss();
        }

    }


}


}

答案 2 :(得分:0)

使用HttpUrlConnection获取JSON,然后解析字符串

示例

// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;
    // Only display the first 500 characters of the retrieved
    // web page content.
    int len = 500;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        Log.d(DEBUG_TAG, "The response is: " + response);
        is = conn.getInputStream();

        // Convert the InputStream into a string
        String contentAsString = readIt(is, len);
        return contentAsString;

    // Makes sure that the InputStream is closed after the app is
    // finished using it.
    } finally {
        if (is != null) {
            is.close();
        } 
    }
}

来源: Connecting to the Network