我目前正在使用以下扩展方法来执行此任务,但似乎应该有一些现有的包含方法或扩展来执行此任务(或至少是其中的一个子集)。如果里面没有任何东西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
以便您能够链接调用(多次调用此扩展或其他方法和扩展)。
i.e.,
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";
see the fiddle https://dotnetfiddle.net/DzFsn9更多细节
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)