C++ Nlohmann JSON:如何检测嵌套对象元素是否存在(无需异常处理)
Great question! Handling JSON property checks without relying on exception handling is not only cleaner but also better for performance—exceptions are expensive, so avoiding them here makes total sense. Let’s walk through how to tackle both your scenarios using the two most common JSON libraries in C#: System.Text.Json (built into .NET Core/.NET 5+) and Json.NET (Newtonsoft.Json).
1. 检测Data对象中"rH"元素是否存在
The key here is to use methods that return a boolean success status instead of throwing exceptions when a property is missing.
Using System.Text.Json
using System.Text.Json; string strJson = "{ \"Header\": {\"Version\":\"V0.00.01\",\"ID\":\"1000\",\"Name\":\"SetEnvValues\"} , \"Data\": {\"Temp\":0.00,\"rH\":0.00,\"CO2\":0.00,\"O2\":0.00 } }"; // Parse the JSON without deserializing to a class using JsonDocument doc = JsonDocument.Parse(strJson); JsonElement root = doc.RootElement; // Check if "Data" exists first, then check for "rH" inside it bool rHExists = root.TryGetProperty("Data", out JsonElement dataElement) && dataElement.TryGetProperty("rH", out _); Console.WriteLine($"rH exists: {rHExists}");
TryGetProperty returns true if the property exists and populates the out parameter; if not, it returns false—no exceptions thrown, exactly what we want.
Using Json.NET (Newtonsoft.Json)
using Newtonsoft.Json.Linq; string strJson = "{ \"Header\": {\"Version\":\"V0.00.01\",\"ID\":\"1000\",\"Name\":\"SetEnvValues\"} , \"Data\": {\"Temp\":0.00,\"rH\":0.00,\"CO2\":0.00,\"O2\":0.00 } }"; JObject jsonObject = JObject.Parse(strJson); // Use null propagation to safely check for nested properties bool rHExists = jsonObject["Data"]?["rH"] != null; Console.WriteLine($"rH exists: {rHExists}");
The ?. operator ensures we don’t get a NullReferenceException if "Data" is missing, and we just check if the final token is non-null to confirm "rH" exists.
2. 检测Data中仅存在的元素(比如只有"Temp"时)
Again, we can use enumeration methods that work with existing properties, no exceptions needed.
Using System.Text.Json
using System.Text.Json; string strJson = "{ \"Header\": {\"Version\":\"V0.00.01\",\"ID\":\"1000\",\"Name\":\"SetEnvValues\"} , \"Data\": {\"Temp\":0.00 } }"; using JsonDocument doc = JsonDocument.Parse(strJson); JsonElement root = doc.RootElement; if (root.TryGetProperty("Data", out JsonElement dataElement)) { // Enumerate all properties in the Data object foreach (JsonProperty property in dataElement.EnumerateObject()) { Console.WriteLine($"Existing property: {property.Name}, Value: {property.Value}"); } }
EnumerateObject() will only iterate over properties that actually exist in the Data object—no need to handle missing keys here.
Using Json.NET (Newtonsoft.Json)
using Newtonsoft.Json.Linq; string strJson = "{ \"Header\": {\"Version\":\"V0.00.01\",\"ID\":\"1000\",\"Name\":\"SetEnvValues\"} , \"Data\": {\"Temp\":0.00 } }"; JObject jsonObject = JObject.Parse(strJson); JToken dataToken = jsonObject["Data"]; if (dataToken is JObject dataObject) { // Loop through all properties in Data foreach (JProperty property in dataObject.Properties()) { Console.WriteLine($"Existing property: {property.Name}, Value: {property.Value}"); } }
Properties() returns only the properties present in the Data JObject, so we can safely iterate without worrying about missing keys.
Key Takeaway
Both libraries provide non-exception-throwing APIs to handle these scenarios:
- For System.Text.Json: Use
TryGetPropertyfor individual checks,EnumerateObjectto list existing properties. - For Json.NET: Use null propagation (
?.) for individual checks,Properties()to list existing properties.
This approach keeps your code clean, performant, and free of unnecessary exception handling.
内容的提问来源于stack exchange,提问作者selbolder

