如何在JObject中添加或更新JProperty值 [英] How do you Add or Update a JProperty Value in a JObject
问题描述
我当前正在使用以下扩展方法来执行此任务,但似乎应该有一些现有的包含方法或扩展来执行此操作(或至少其中一部分).如果 Json.NET 中没有任何内容,那么推荐的过程是什么,或者我将如何更改下面的代码以使其更接近推荐的过程.
I am currently using the following extension method to perform this task, but it almost seems like there should be some existing included method or extension to perform this (or at least a subset of this). If there isn't anything within Json.NET then what is the recommended process, or how would I change the code below to be closer to the recommended process.
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;
}
}
我可以确认上面的代码适用于基本用法,但是我不确定它能否在更广泛的使用范围内发挥作用.
I can confirm the above code works for basic usage, but I'm not certain how well it holds up to broader usage.
我让此扩展名返回JObject
的原因是,您可以链接调用(对此扩展名或对其他方法和扩展名的多次调用).
The reason I have this extension returning a JObject
is so that you would be able to chain calls (either multiple calls to this extension or to other methods and extensions).
即
var data = JObject.Parse("{ 'str1': 'test1' }");
data
.SetPropertyContent("str1", "test2")
.SetPropertyContent("str3", "test3");
// {
// "str1": "test2",
// "str3": "test3"
// }
推荐答案
如注释中的@dbc所述,您只需使用索引器即可实现此目的.
as @dbc described in the comment, you can simply use the indexer to make this happen.
var item = JObject.Parse("{ 'str1': 'test1' }");
item["str1"] = "test2";
item["str3"] = "test3";
有关更多详细信息,请参见小提琴
see the fiddle for more details
这篇关于如何在JObject中添加或更新JProperty值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!