2013-02-25 2 views
0

У меня есть asp.net-web-api проект со следующим GET способом:Обращение в нуль Json

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(); 
     } 
    } 

при просмотре в api адреса с светлячок я получаю этот «нуль» для нулевых значений и правильного Json для правильных запросов.
null json
исключением я получаю org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONObject. Как я могу сделать операторы If поймать нулевой json?

+0

Я вижу недостающий разделитель точку с запятой в конце ' "пароль = 1234"'. –

+0

Пожалуйста, разместите фактический JSON, полученный от активности. –

+0

@BrianRoach Как? – Yoav

ответ

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; 
} 

вы передаете строку от сервера к JSONObject конструктора и ловить исключение, если строка не является допустимым JSON.

json=new JSONObject(result); 

можно, например, добавить такое условие:

if ("null".equals(result)) { 
    //do something with null 
} else { 
    json = new JSONObject(result); 
} 
Смежные вопросы