Search code examples
c#jsonsystem.text.jsonjsonnode

JsonNode.HasProperty returns false when value is null


So I am writing a wrapper for JsonNode to easier extract json properties when there is no data-contract and I need to support a plethora of different values. But I am having some issues when it comes to reading an empty value. So either I am doing something wrong, or JsonNode is the wrong class to work with here.

My test-json is the following:

{
  "id": 3,
  "name": null
}

And I am doing different kind of queries against the JsonNode.

_node.HasProperty("id") will return true, but _node.HasProperty("name") will return false.

So is there a way to achieve this?

Please advice.


Solution

  • You'll need to cast the JsonNode to the derived JsonObject type and use the ContainsKey method.

    JsonObject jsObj = _node.AsObject();
    bool hasProperty = jsObj.ContainsKey("name");