如何在JObject中添加或更新JProperty值

我目前正在使用以下扩展方法来执行此任务,但似乎应该有一些现有的包含方法或扩展来执行此操作(或至少是其中的一部分)。 如果Json.NET中没有任何内容,那么建议的过程是什么,或者我如何更改下面的代码以更接近推荐的过程。

public static partial class ExtensionMethods { public static JObject SetPropertyContent(this JObject source, string name, object content) { var prop = source.Property(name); if (prop == null) { prop = new JProperty(name, content); source.Add(prop); } else { prop.Value = JContainer.FromObject(content); } return source; } } 

我可以确认上面的代码适用于基本用法,但我不确定它是否适用于更广泛的用法。

我有这个扩展返回一个JObject的原因是你可以链接调用(对这个扩展或其他方法和扩展的多次调用)。

 var data = JObject.Parse("{ 'str1': 'test1' }"); data .SetPropertyContent("str1", "test2") .SetPropertyContent("str3", "test3"); // { // "str1": "test2", // "str3": "test3" // } 

正如评论中描述的@dbc,你可以简单地使用索引器来实现这一点。

 var item = JObject.Parse("{ 'str1': 'test1' }"); item["str1"] = "test2"; item["str3"] = "test3"; 

看到小提琴了解更多细节