JavaEar 专注于收集分享传播有价值的技术资料

Check property exists to stop error; cannot access child value on Newtonsoft.Json.Linq.JProperty

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 code:

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

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

End If

Error:

Cannot access child value on Newtonsoft.Json.Linq.JProperty

How can I check the property exists to make sure not to trigger the error when it's not available?

1个回答

    最佳答案
  1. The property named free_domains does exist in your jsonObj and if you check the return value of jsonObj.[Property]("free_domains"), it does contain an appropriate object.

    The point is that jsonObj.[Property]("free_domains") returns an object of type JProperty, which is a property descriptor. This descriptor does not represent the property value directly. In order to access this value, use JProperty.Value:

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

    There is an easier way to access the value, though. Use the string indexer of the jsonObj:

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

    To check if a property exists, check if the value returned by the string indexer is not Nothing. Null-conditional operator may prove handy when accessing a series of properites in a hierarchy:

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