0

我有一个asp.net-web-api使用以下GET方法的项目:

 public string Get(string id)
    {
        List<dummy> dummies = new List<dummy>();
        string con = "user id=sa;" +
                     "password=1234" +
                     "server=foo\\bar;" +
                     "database=game; " +
                     "connection timeout=30";

        //SqlConnection sqlConn = new SqlConnection(con);
        using (SqlConnection sqlconn = new SqlConnection(con))
        {
            sqlconn.Open();
            StringBuilder sb = new StringBuilder();
            sb.Append("SELECT PART.PARTNAME,PART.PARTDES, PARTPARAMA.LOCATION ");
            sb.Append("FROM PART LEFT JOIN PARTPARAMA ");
            sb.Append("ON PART.PART = PARTPARAMA.PARTPARAM ");
            sb.Append("WHERE PART.PARTNAME = @part");


            using (SqlCommand cmd = new SqlCommand(sb.ToString(), sqlconn))
            {
                cmd.Parameters.AddWithValue("part", id);
                SqlDataReader sdr = cmd.ExecuteReader();
                while (sdr.Read())
                {
                    dummies.Add(new dummy
                    {
                        PartName = sdr.GetString(0),
                        PartDes = sdr.GetString(1),
                        PartLocation = sdr.GetString(2)
                    });
                }
            }
        }

        if (dummies.Count() > 0)
        {
            string json = JsonConvert.SerializeObject(dummies[0]);
            return json;
        }
        else
        {
            string json = JsonConvert.SerializeObject(null);
            return json;
        }
    }

(我json.net用于序列化)。

然后Android Activity使用它(删除不相关的部分):

public class MainActivity extends Activity {

    String tempResult = "";
    JSONObject tempJo;

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

        try {
            tempJo = mc.execute(someString).get();

            } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
        //Tried to check for null with the following
        //if(aaa == null)
        //{
        //  Toast.makeText(context, "clear null", Toast.LENGTH_LONG).show();
        //}
        //if(aaa == "null")
        //{
        //  Toast.makeText(context, "null", Toast.LENGTH_LONG).show();
        //}
        //if(aaa == "\"null\"")
        //{
        //  Toast.makeText(context, "special null", Toast.LENGTH_LONG).show();
        //}
        //if(aaa=="{}")
        //{
        //  Toast.makeText(context, "empty", Toast.LENGTH_LONG).show();
        //}
        if(tempJo.toString() == null)
        {
            Toast.makeText(context, "tempJo is null", Toast.LENGTH_LONG).show();
        }
        else
        {
            PartDetails pd = getPart(tempResult);
            txtPart.setText(pd.partName);
            txtDescription.setText(pd.partDescription);
            txtLocation.setText(pd.partLocation);
        }

    }
    private PartDetails getPart(String json){
        Toast.makeText(this, "*** the json value is: ***: " + json, Toast.LENGTH_LONG).show();
        PartDetails pd = new PartDetails();
        try {
            Toast.makeText(context, "got here!!!", Toast.LENGTH_LONG).show();

            JSONObject jo = new JSONObject(json);

            pd.partName = jo.getString("PartName");
            pd.partDescription = jo.getString("PartDes");
            pd.partLocation = jo.getString("PartLocation");

        } catch (JSONException e1) {
            Toast.makeText(this, "*** JSONException ***: " + e1.getMessage(), Toast.LENGTH_LONG).show(); <=> Exception is here
        }
        return pd;
    }

    public class myClass extends AsyncTask<String, Void, JSONObject>{

        protected JSONObject doInBackground(String... passing) {
            String url = "http://1.2.3.4/api1/api/values/" + passing[0];
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url); 
            HttpResponse response;
            JSONObject json = new JSONObject();

            try{
                response = httpclient.execute(httpget);
                HttpEntity entity = response.getEntity();
                if(entity != null){
                    InputStream instream = entity.getContent();
                    String result= convertStreamToString(instream);
                    json=new JSONObject(result);
                    instream.close();
                }
            }
            catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

                return json;
        }

        public String convertStreamToString(InputStream is) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();

            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return sb.toString();
        }
    }

当使用 firefox 浏览api地址时,我得到这个“null”的空值和Json正确的查询。
空json
我得到的例外是org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONObject。我怎样才能让If语句捕获空 json?

4

1 回答 1

0

这是您的代码:

protected JSONObject doInBackground(String... passing) {
    String url = "http://1.2.3.4/api1/api/values/" + passing[0];
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url); 
    HttpResponse response;
    JSONObject json = new JSONObject();
    try {
        response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        if(entity != null){
            InputStream instream = entity.getContent();
            String result= convertStreamToString(instream);
            json=new JSONObject(result);
            instream.close();
        }
    }
    catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

        return json;
}

如果您的字符串不是有效的 json,则您正在将字符串从服务器传递到 JSONObject 构造函数并捕获异常。

json=new JSONObject(result);

例如,您可以添加这样的条件:

if ("null".equals(result)) {
     //do something with null
} else {
    json = new JSONObject(result);
}
于 2013-02-25T15:06:57.420 回答