如何在Java中检查JSON对象是否为null

时间:2015-05-13 19:49:04

标签: java json

我正在开发一个在我的服务器上执行搜索的应用程序,数据传输基于JSON,但是我在解析结果时遇到问题,如果没有网络,我从JSON对象获取信息时会收到NullException ,我尝试检查连接,如果连接到互联网然后它可以继续,但在请求数据时它有互联网的情况下,当从服务器接收它时丢失它我也得到NullException,我认为是检查是否JSON在使用它进行调整之前,对象是null,但是我知道所有检查null的方法都失败了,下面是我的JAVA代码:

 mCommentList = new ArrayList<HashMap<String, String>>();


            try {

                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("query", searchbox.getText().toString()));


                Log.d("request!", "starting Search");
                // getting product details by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(SEARCH_URL, "POST",
                        params);

                // check your log for json response
               if(json.toString().isEmpty())
                {
                   Log.d("Search Attempt", json.toString());
               }

               else{
                   search = new SEARCH();
                    search.cancel(true);



                }

                Log.d("Search Attempt", json.toString());

1 个答案:

答案 0 :(得分:-2)

请下载必要的JUnit JAR文件以启用断言

mCommentList = new ArrayList<HashMap<String, String>>();


            try {

                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("query", searchbox.getText().toString()));


                Log.d("request!", "starting Search");
                // getting product details by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(SEARCH_URL, "POST",
                        params);

                 AssertNotNull(json); //for asserting 

                 // To prevent the code form breaking 
                // check your log for json response
               if(json.toString().isEmpty())
                {
                   Log.d("Search Attempt", json.toString());
               }

               else{
                   search = new SEARCH();
                    search.cancel(true);



                }

                Log.d("Search Attempt", json.toString());