json.parse允许null或missing

时间:2014-02-23 03:39:33

标签: json vb.net string url null

我的JSON字符串

{

"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字符串和代码以便于阅读,但我的问题是有一种方法来处理错误,当字符串中缺少“status”并继续解析其余的对象?

或者如果在缺少此值时可以使用/ null将其替换为其他内容但是如果选择了此路由,我想为每个路由设置不同的值。

1 个答案:

答案 0 :(得分:1)

在执行jResults("status")之前,检查Nothing和其他属性是否为空(.ToString())。

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