如何用Newtonsoft.Json.Linq获取JSON中Data节点下带Symbol属性的元素?
Symbol Property from the Data Node Using Newtonsoft.Json.Linq Hey Ronald, no worries at all—let's break this down step by step so you can easily grab those elements with the Symbol property using Newtonsoft.Json.Linq (often called JLinq). Here's a straightforward approach:
Step 1: Parse the JSON into a JObject
First, we need to convert your JSON string into a JObject instance, which lets us navigate and query the JSON structure easily.
Step 2: Access the Data Node
Next, we'll pull out the Data node from the root JObject. We'll cast it to JObject to ensure we're working with a collection of key-value pairs.
Step 3: Filter Elements with the Symbol Property
We'll iterate over all child elements in the Data node, then filter out any that don't have the Symbol property. Since each entry in Data is a key-value pair (like "42": { ... }), we'll use Children<JProperty> to access each entry, then extract its value as a JObject.
Full Code Example
using Newtonsoft.Json.Linq; using System; using System.Linq; class Program { static void Main() { // Your original JSON string string json = @"{ ""prop1"": ""bla"", ""propn"": ""bla"", ""Data"": { ""42"": { ""prop1"": ""bla"", ""prop2"": ""bla"", ""Symbol"": ""42"" }, ""abc"": { ""prop1"": ""bla"", ""prop2"": ""bla"", ""Symbol"": ""abc"" } }, ""Type"": 100 }"; // Parse the JSON into a JObject JObject rootObj = JObject.Parse(json); // Get the Data node (cast to JObject to ensure we can iterate over its children) if (rootObj["Data"] is JObject dataNode) { // Filter all elements in Data that have a Symbol property var elementsWithSymbol = dataNode.Children<JProperty>() .Select(prop => prop.Value as JObject) .Where(obj => obj != null && obj.ContainsKey("Symbol")); // Process each matching element foreach (var element in elementsWithSymbol) { string symbolValue = element["Symbol"].ToString(); string prop1Value = element["prop1"].ToString(); Console.WriteLine($"Found element with Symbol: {symbolValue} | Prop1: {prop1Value}"); } } else { Console.WriteLine("Data node not found or is not an object."); } } }
Key Notes:
- Null Safety: We check if
rootObj["Data"]is a validJObjectand if each child value is aJObjectto avoid null reference exceptions. - Flexible Filtering: The
Whereclause lets you add extra conditions if needed (e.g., checking ifSymbolhas a specific value). - Accessing Values: Use
ToString()for string values, orToObject<T>()if you need to convert to other types (likeintfor a numeric Symbol).
If you need to do something specific with these elements (like map them to a C# class), you can extend this code by using element.ToObject<YourClass>() where YourClass has properties matching the JSON structure.
内容的提问来源于stack exchange,提问作者Ronald

