0

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.

6
  • I think you'll have to parse it to a JsonObject and use ContainsKey("name") Commented Aug 6, 2024 at 16:38
  • Pls. provide more code along with data for clarity. Commented Aug 6, 2024 at 18:18
  • 1
    @hakim00 - You were right on the money my friend. The easiest way was to use _node.AsObject() to get an instance of the JsonObject, and then use ContainsKey() just like you said. Please add a reply here and Ill mark it as the correct answer. Commented Aug 8, 2024 at 11:58
  • What is the HasProperty method? Where does it come from? I'm not able to find it through Methods of neither JsonNode nor JsonObject. You need to check your code for the HasProperty definition. Commented Aug 8, 2024 at 12:57
  • @Thomas I've added a reply, but I'm also curious about the HasProperty implementation, as this was suggested here github.com/dotnet/runtime/issues/47649#issuecomment-812123225 but never implemented. Commented Aug 8, 2024 at 16:29

2 Answers 2

2

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");
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for pointing out. You are correct, I meant casting it.
1

On my guess, the obtained result means that currently processed JsonNode is "id": 3 only. You need to come back to the root of current JsonNode and get the "name" node.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.