How can I check that a JSON value is an object with the keys I need?
Quick answer
With .NET's System.Text.Json, check the root JsonElement.ValueKind against JsonValueKind.Object first. If it is not an object, report that and stop; only then use TryGetProperty for each required key and report missing names. These checks establish the root type and key presence, not whether the values have the right types or meaningful contents.
The question, the details, the next step.
A practical checklist
Define the required property names for your input contract.
Check that the root
ValueKindisObjectbefore property lookup.If the root is not an object, report that problem and stop this check.
Use
TryGetPropertyfor every required name and collect all missing names.Validate value types, nullability, and content separately if your contract requires them.
Test a wrong-kind root, a complete object, and objects with missing keys.
A few more useful answers
Does this check validate nested objects too?
No. It checks only the root and the required top-level keys shown. Validate nested values separately if your input contract requires them.
Can I use this example with any JSON library or programming language?
No. JsonElement, ValueKind, and TryGetProperty are .NET System.Text.Json APIs. The cited documentation does not establish equivalent behavior for other libraries.
What does an empty missing-key list prove?
It proves only that the required property names were found on the checked object. It does not prove that their values have acceptable types or contents.
Sources
References used for this guide.
- [S1] JsonElement.ValueKind Property (System.Text.Json) learn.microsoft.com · Checked
- [S2] JsonElement.TryGetProperty Method (System.Text.Json) learn.microsoft.com · Checked
