2014-02-23 149 views
0

MY JSON字符串json.parse允許空或丟失

{ 

"name": "username", 
"status": "mystatus", 
"place": { 
"name": "placename", 
}  

我的代碼

Dim request As HttpWebRequest 
    Dim response As HttpWebResponse = Nothing 
    Dim reader As StreamReader 

    Try 

     request = DirectCast(WebRequest.Create("http://myjsonstring.com/json"), HttpWebRequest) 

     response = DirectCast(request.GetResponse(), HttpWebResponse) 
     reader = New StreamReader(response.GetResponseStream()) 

     Dim rawresp As String 
     rawresp = reader.ReadToEnd() 

     Dim jResults As JObject = JObject.Parse(rawresp) 
     if (rawresp != null) 
      name.Text = jResults("name").ToString() 
      status.Text = jResults("status").ToString() 
      placename.Text = jResults("place")("name").ToString() 

    End If 

    Catch ex As System.Net.WebException 
     MsgBox(ex.ToString) 

    Finally 
     If Not response Is Nothing Then response.Close() 

    End Try 

我的問題是,有時我的JSON可能看起來像這樣

{ 

"name": "username", 
"place": { 
"name": "placename", 
} 

我的JSON解釋

"name": "name here", 
    "items": { 
    "myitem": { 
     "icon": "myitem.jpg", 
    "myitem2": { 
     "icon": "myitem2.jpg", 
} 

我的代碼我已經試過

myitem.Text = If(jResults2("items")("myitem")("icon") Is Nothing, "", jResults2("items")("myitem")("icon").ToString()) 
myitem2.Text = If(jResults2("items")("myitem2")("icon") Is Nothing, "", jResults2("items")("myitem2")("icon").ToString()) 

當值從myitem缺少它停止JSON和myitem2永遠不會顯示。

發生這種情況我的項目拋出一個空值異常,我已嚴厲地壓縮了我的json字符串和代碼的可讀性,但我的問題是有一種方法來處理錯誤,當「狀態」從字符串中丟失並繼續解析其餘的對象?

或者,如果它可能的時候這個值是缺失/ null替換它的東西,但如果這條路線被選中,我想爲每個設置一個不同的值。

+1

在執行'.ToString()'之前,檢查'jResults(「status」)'爲null('Nothing')。 –

回答

1

在做.ToString()之前檢查jResults("status")和其他屬性是否爲空(Nothing)。

Dim jResults As JObject = JObject.Parse(rawresp) 
name.Text = If(jResults("name") Is Nothing, "", jResults("name").ToString()) 
status.Text = If(jResults("status") Is Nothing, "", jResults("status").ToString()) 
placename.Text = If(jResults("place") Is Nothing, "", jResults("place")("name").ToString()) 
+0

非常感謝你 – ids

+0

啊,它似乎沒有工作,因爲它的唯一的返回空值,即使當狀態是在字符串 謝謝 – ids

+0

所以,如果你改變了'status.Text = If(jResults (「status」)是Nothing,「」,jResults(「status」)。ToString())'回到'status.Text = jResults(「status」)。ToString()',它的工作原理? –