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 値の場合はこの「null」が表示されJson、正しいクエリの場合は正しい値が表示されます。
ヌル json
私が得ている例外はですorg.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONObjectIfステートメントでnull 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 に答える