【发布时间】:2015-05-06 19:33:09
【问题描述】:
我目前正在使用以下扩展方法来执行此任务,但似乎应该有一些现有的包含方法或扩展来执行此任务(或至少是其中的一个子集)。如果 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"
// }
【问题讨论】:
-
你怎么知道你在做的是
wrong..? or not correct听起来codereview就是你想要的 -
代码审查就是这个样子
-
tbh,我还没有 codereview 的负责人,有没有简单的方法把它移到那里?
-
你可以做
source[name] = JToken.FromObject(content),它会根据需要添加或设置。