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

pjs*_*pjs 16 c# json json.net

我目前正在使用以下扩展方法来执行此任务,但似乎应该有一些现有的包含方法或扩展来执行此操作(或至少是其中的一部分).如果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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

var data = JObject.Parse("{ 'str1': 'test1' }");

data
    .SetPropertyContent("str1", "test2")
    .SetPropertyContent("str3", "test3");

// {
//   "str1": "test2",
//   "str3": "test3"
// }
Run Code Online (Sandbox Code Playgroud)

pjs*_*pjs 30

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

var item = JObject.Parse("{ 'str1': 'test1' }");

item["str1"] = "test2";
item["str3"] = "test3";
Run Code Online (Sandbox Code Playgroud)

看到小提琴了解更多细节


小智 5

任何尝试访问嵌套 JSON 的人都可以使用@pjs回答中的方法,根据需要添加额外的大括号。

JObject item = JObject.Parse("{
   "test": {
       "first": "one",
       "second": "two",
       "nth":   "n"
   }
}");
Run Code Online (Sandbox Code Playgroud)

编辑:

item["test"]["nth"] = "updated";
Run Code Online (Sandbox Code Playgroud)

将 JObject 更新为:

{
   "test": {
       "first": "one",
       "second": "two",
       "nth":   "updated"
   }
}
Run Code Online (Sandbox Code Playgroud)