【问题标题】:Check property exists to stop error; cannot access child value on Newtonsoft.Json.Linq.JProperty检查属性是否存在以停止错误;无法访问 Newtonsoft.Json.Linq.JProperty 上的子值
【发布时间】:2017-06-10 04:24:30
【问题描述】:

JSON:

{
  "status": "OK",
  "maximum_reached": 0,
  "top_domain": {
    "dont_show": 1
  },
  "free_domains": [
    {
      "status": "AVAILABLE",
      "domain": "go",
      "tld": ".tk",
      "currency": "USD",
      "type": "SPECIAL",
      "price_int": "1000",
      "price_cent": "00",
      "show_top_domain": 0,
      "is_in_cart": 0
    },
  ]
}

VB.NET 代码:

Dim jsonObj As JObject = JObject.Parse(hr.Html)

If IsNothing(jsonObj.[Property]("free_domains")(0)("status")) Then

End If

错误:

无法访问 Newtonsoft.Json.Linq.JProperty 上的子值

如何检查属性是否存在以确保在不可用时不会触发错误?

【问题讨论】:

    标签: json vb.net linq json.net


    【解决方案1】:

    jsonObj 中确实存在名为free_domains 的属性,如果您检查jsonObj.[Property]("free_domains") 的返回值,它确实包含适当的对象。

    重点是jsonObj.[Property]("free_domains")返回一个JProperty类型的对象,它是一个属性描述符。此描述符不直接表示属性值。要访问此值,请使用JProperty.Value

    jsonObj.[Property]("free_domains").Value(0)("status")
    

    不过,有一种更简单的方法可以访问该值。使用jsonObj的字符串索引器:

    jsonObj("free_domains")(0)("status")
    

    要检查属性是否存在,请检查字符串索引器返回的值是否不是Nothing。在访问层次结构中的一系列属性时,空条件运算符可能会很方便:

    If IsNothing(jsonObj("free_domains")?(0)?("status")) Then
    
    End If
    

    【讨论】:

    • 您的回答帮助我解决了类似的问题。
    猜你喜欢
    • 2021-08-23
    • 2012-04-18
    • 2023-03-24
    • 2018-03-10
    • 2019-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多