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替換它的東西,但如果這條路線被選中,我想爲每個設置一個不同的值。
在執行'.ToString()'之前,檢查'jResults(「status」)'爲null('Nothing')。 –