2014-02-24 117 views
0

我的JSON允許空值,並繼續

{ 

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

我的代碼

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

    Try 

     request = DirectCast(WebRequest.Create("http://myjson.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) 
     name.Text = If(jResults2("name") Is Nothing, "", jResults2("name").ToString()) 
     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()) 



     'Catch ex As Exception 
    Catch ex As System.Net.WebException 
     MsgBox(ex.ToString) 
    Finally 
     If Not response Is Nothing Then response.Close() 

    End Try 

IM有我的JSON一個問題,有時也可以是這樣的

{ 

"name": "username", 
    "items": { 
    "myitem2": { 
     "icon": "myitem2.jpg", 
} 

當我做如果myitem不在json字符串中,則檢查爲null,然後將名稱放在name.text中,但myitem2未處理或甚至放置在myitem2.Text中

任何幫助解決這一問題將是短期巨大的,如果myitem爲null,我仍然希望它繼續處理項目

+0

JSON無效,您的JSON RootObject類是什麼樣的? – Dayan

回答

0

的JSON在你的例子是無效的休息,你可以訪問這個網站驗證您的JSON:http://jsonlint.com/

我想你想要的東西有如下所示:

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

如果這是正確的,那麼你的這個JSON RootObject會看起來像這樣:

public class Myitem 
{ 
    public string icon { get; set; } 
} 

public class Myitem2 
{ 
    public string icon { get; set; } 
} 

public class Items 
{ 
    public Myitem myitem { get; set; } 
    public Myitem2 myitem2 { get; set; } 
} 

public class RootObject 
{ 
    public string name { get; set; } 
    public Items items { get; set; } 
} 
+0

是的抱歉,我沒有正確輸入。但我不認爲我理解爲我發佈在我的代碼它'name.Text = If(jResults2(「name」)是Nothing,「」,jResults2(「name」)。ToString()) myitem.Text = If (jResults2(「items」)(「myitem」)(「icon」)is Nothing,「」,jResults2(「items」)(「myitem」)(「icon」))ToString()) myitem2.Text = If (jResults2(「items」)(「myitem2」)(「icon」)是Nothing,「」,jResults2(「items」)(「myitem2」)(「icon」)。ToString())'我怎麼能設置它所以當它通過json時,如果缺少某些東西,它會跳過它並繼續其餘部分 – ids

相關問題