


























C# 中的 JObject 是 Newtonsoft.Json(Json.NET)库中的核心类,用于动态操作 JSON 数据。
using Newtonsoft.Json.Linq; // 方式1:直接创建 JObject obj = new JObject(); obj["name"] = "John"; obj["age"] = 30; // 方式2:从字符串解析 string json = @"{'name': 'John', 'age': 30}"; JObject obj = JObject.Parse(json); // 方式3:从对象创建 var person = new { Name = "John", Age = 30 }; JObject obj = JObject.FromObject(person);
JObject obj = JObject.Parse(@"{ 'name': 'John', 'age': 30, 'address': { 'city': 'Beijing', 'zip': '100000' }, 'hobbies': ['reading', 'coding'] }"); // 基础访问 string name = (string)obj["name"]; // "John" int age = (int)obj["age"]; // 30 // 嵌套对象 string city = (string)obj["address"]["city"]; // "Beijing" // 数组 JArray hobbies = (JArray)obj["hobbies"]; string firstHobby = (string)hobbies[0]; // "reading" // 安全访问(防止 null) string zip = obj["address"]?["zip"]?.Value<string>(); // "100000"
JObject obj = JObject.Parse(@"{'name': 'John', 'age': 30}"); // 修改 obj["age"] = 31; // 添加新字段 obj["email"] = "john@example.com"; // 添加嵌套对象 obj["profile"] = new JObject { ["avatar"] = "http://example.com/avatar.jpg", ["level"] = 5 }; // 添加数组 obj["tags"] = new JArray("vip", "active"); // 删除字段 obj.Remove("age"); // 输出 JSON string json = obj.ToString(); // 或压缩格式 string compact = obj.ToString(Newtonsoft.Json.Formatting.None);
string json = @"{ 'stores': [ { 'name': 'Store A', 'products': [ { 'name': 'Apple', 'price': 5 }, { 'name': 'Banana', 'price': 3 } ]}, { 'name': 'Store B', 'products': [ { 'name': 'Orange', 'price': 4 } ]} ] }"; JObject data = JObject.Parse(json); // 查询所有产品价格大于3的产品 var expensiveProducts = data["stores"] .SelectMany(s => s["products"]) .Where(p => (decimal)p["price"] > 3) .Select(p => new { Name = (string)p["name"], Price = (decimal)p["price"] }); foreach (var product in expensiveProducts) { Console.WriteLine($"{product.Name}: {product.Price}"); }
JObject obj1 = JObject.Parse(@"{'a': 1, 'b': 2}"); JObject obj2 = JObject.Parse(@"{'b': 3, 'c': 4}"); // 合并(obj2 覆盖 obj1 的相同键) obj1.Merge(obj2, new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Union }); // 结果: {'a': 1, 'b': 3, 'c': 4}
JObject original = JObject.Parse(@"{'name': 'John'}"); JObject clone = (JObject)original.DeepClone(); clone["name"] = "Jane"; // original["name"] 仍然是 "John"
dynamic obj = JObject.Parse(@"{'name': 'John', 'age': 30}"); string name = obj.name; // "John" int age = obj.age; // 30 // 甚至可以动态添加 obj.email = "john@example.com";
public class Person { public string Name { get; set; } public int Age { get; set; } } // JObject -> 实体类 JObject jsonObj = JObject.Parse(@"{'name': 'John', 'age': 30}"); Person person = jsonObj.ToObject<Person>(); // 实体类 -> JObject Person p = new Person { Name = "Jane", Age = 25 }; JObject backToJson = JObject.FromObject(p);
using Newtonsoft.Json.Linq; class Program { static void Main() { string json = @"{ 'store': { 'book': [ { 'category': 'reference', 'author': 'Nigel Rees', 'title': 'Sayings of the Century', 'price': 8.95 }, { 'category': 'fiction', 'author': 'Evelyn Waugh', 'title': 'Sword of Honour', 'price': 12.99 }, { 'category': 'fiction', 'author': 'Herman Melville', 'title': 'Moby Dick', 'price': 8.99 } ], 'bicycle': { 'color': 'red', 'price': 19.95 } }, 'expensive': 10 }"; JObject obj = JObject.Parse(json); // 1. 获取所有书的作者 Console.WriteLine("所有作者:"); foreach (var author in obj.SelectTokens("$.store.book[*].author")) { Console.WriteLine($" {author}"); } // 2. 获取价格小于10的书 Console.WriteLine("\n便宜的书 (<10):"); foreach (var book in obj.SelectTokens("$.store.book[?(@.price < 10)]")) { Console.WriteLine($" {book["title"]}: {book["price"]}"); } // 3. 获取最后一本书 var lastBook = obj.SelectToken("$.store.book[-1:]"); Console.WriteLine($"\n最后一本书: {lastBook["title"]}"); // 4. 获取所有价格(递归) Console.WriteLine("\n所有价格:"); foreach (var price in obj.SelectTokens("$..price")) { Console.WriteLine($" {price}"); } // 5. 获取 fiction 类别的书 Console.WriteLine("\n小说类:"); foreach (var book in obj.SelectTokens("$.store.book[?(@.category == 'fiction')]")) { Console.WriteLine($" {book["title"]}"); } } }


.NET 6+ 推荐使用 System.Text.Json 的 JsonNode 作为替代:
// System.Text.Json 方式 using System.Text.Json.Nodes; JsonNode node = JsonNode.Parse(@"{'name': 'John'}"); node["age"] = 30;
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。