如何使用Json.Net结合JSONPath获取嵌套JSON的属性名?
Short answer: No, Newtonsoft.Json's built-in JSONPath implementation doesn't support the ~ syntax (used in libraries like JSONPath-Plus) to retrieve property names directly.
For your specific example JSON:
{"fields": {"hum": 48.1, "temp": 24.4}}
If you need to get the property names hum and temp in .NET Core, here are two straightforward alternatives using Newtonsoft.Json:
1. Directly parse and traverse the JObject
This is the simplest and most efficient approach—no JSONPath required:
using Newtonsoft.Json.Linq; using System.Linq; // Parse your JSON string var jsonString = @"{""fields"": {""hum"": 48.1, ""temp"": 24.4}}"; var rootObject = JObject.Parse(jsonString); // Access the "fields" object and get its property names if (rootObject.TryGetValue("fields", out JToken fieldsToken) && fieldsToken is JObject fieldsObject) { var propertyNames = fieldsObject.Properties().Select(p => p.Name); // Iterate over the names or use them as needed foreach (var name in propertyNames) { Console.WriteLine(name); // Outputs: hum, temp } }
2. Why JSONPath ~ doesn't work with Newtonsoft.Json
Newtonsoft.Json's JSONPath implementation adheres to the original JSONPath specification by Stefan Goessner. The ~ operator is an extension added by libraries like JSONPath-Plus, which isn't part of the standard spec Newtonsoft follows. So there's no built-in way to use that syntax with Newtonsoft.Json.
If you really want to use a JSONPath-like approach with property name retrieval, you'd need to either:
- Implement a custom JSONPath evaluator that adds support for
~ - Use a third-party .NET library that supports extended JSONPath features (though most popular ones stick to the standard spec)
But for your use case, directly traversing the JObject is the most practical solution in .NET Core.
内容的提问来源于stack exchange,提问作者Georges Legros

