【问题标题】:Parsing Json using Vb.net Json.NET使用 Vb.net Json.NET 解析 Json
【发布时间】:2014-11-19 19:14:01
【问题描述】:

大家好,我在代码中随机出现以下错误:

对象引用未设置为对象的实例。

我知道我为什么会得到它。它没有找到我正在寻找的正确属性,因此它给出了错误。有些可能具有该属性,而有些则如此错误所示,可能没有。

我可以做些什么来首先检查以确保它具有该属性?目前我只有一个 Try/catch 方法,所以如果它确实找到了不存在的东西,它可以继续运行。

For Each Row In json("data")
  Try
    thePostID = DirectCast(Row("id").ToString(), String)
    thePostType = DirectCast(Row("type").ToString(), String)
    thePosterID = DirectCast(Row("from")("id").ToString(), String)
    thePosterName = DirectCast(Row("from")("name").ToString(), String)
  Catch ex As NullReferenceException
    msgbox("Did not find that particular property!")
  End Try
Next

更新

{
"data": [
 {
   "id": "102zzz533zz_10z52zz9zzzz94z3", 
   "from": {
     "id": "102zzzzz95zzz7", 
     "name": "Jim zzzzz"
 }, 
 "likes": {
    "data": [
      {
        "id": "85zzzzz35zzzz0", 
        "name": "Anna zzzzz"
      }, 
      {
        "id": "10zzzz93z31zzzzz", 
        "name": "Vanessa zzzz zzzz"
      }, 
      {
        "id": "1zzz44zzz48731z6", 
        "name": "Leta zzzzzz"
      }
    ], 
    "paging": {
      "cursors": {
        "after": "MTAyMdfasdfwrtMTkyNg=", 
        "before": "ODUasdfasrU5Mwerw"
      }
    }
  }
etc...

上面的这个 JSON 与所有其他 JSON 遵循相同的 data 路径。

使用下面的@Andrews 代码:

thePostLikes = NullSafeSelect(Row, "likes.data.id")

If thePostLikes <> "NA" Then
   For Each Row2 In json("likes")("data")
      thePostLikesID += NullSafeSelect(Row2, "id") & ","
      thePostLikesName += NullSafeSelect(Row2, "name") & ","
   Next
End If

thePostLikes 的值始终是Nothing

【问题讨论】:

    标签: json vb.net json.net nullreferenceexception


    【解决方案1】:

    在 JSON.NET 中可能有一种更优雅的方式来执行此操作,但这里有一个辅助函数,如果您提供的 path 不存在,它将只返回 Nothing

    Function NullSafeSelect(ByVal obj As JToken, ByVal path As String) As String
        Dim result As String = Nothing
        Dim value As JToken = obj.SelectToken(path, False)
    
        if (value IsNot Nothing)
            result = value.ToString()
        End If
    
        Return value
    End Function
    

    你可以像这样从你的循环中调用它:

    For Each row in json("data")
        Dim thePostID As String = NullSafeSelect(row, "id")
        Dim thePostType As String = NullSafeSelect(row, "type")
        Dim thePosterId As String = NullSafeSelect(row, "from.id")
        ' ... etc
    
    Next
    

    请注意,您不需要DirectCast,因为函数的返回类型已经是String

    【讨论】:

    • 好吧,但是 DirectCast(Row("likes")("data")("id").ToString(), String)DirectCast( Row("from")("id").ToString(), String)?它似乎只能从你的函数中得到一个。
    • @StealthRT:你能展示你的 JSON 吗?如果likes 是一个数组,您需要将该值作为数组检索并遍历它
    • 这就像你现在所做的那样......只是为了路径而不是仅仅 ("soemthing") 它需要是 (something)(something )(某事).
    • @StealthRT:你应该可以使用likes.data.id,假设likes是一个对象——你可以使用相当复杂的路径
    • 看看我的 OP 更新。我发布了其他 json 代码,因为我似乎无法让它工作。
    猜你喜欢
    • 2014-03-05
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-08
    相关资源
    最近更新 更多