【问题标题】:How do you Add or Update a JProperty Value in a JObject如何在 JObject 中添加或更新 JProperty 值
【发布时间】: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),它会根据需要添加或设置。

标签: c# json json.net


【解决方案1】:

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

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

item["str1"] = "test2";
item["str3"] = "test3";

查看fiddle了解更多详情

【讨论】:

  • 太棒了。但是,如果我想通过 LINQ 添加或更新,我应该怎么做?
  • 我假设您只需 foreach 您的枚举并使用上述解决方案添加或更新您的枚举中的每个元素。
【解决方案2】:

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

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

编辑:

item["test"]["nth"] = "updated";

将 JObject 更新为:

{
   "test": {
       "first": "one",
       "second": "two",
       "nth":   "updated"
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 2021-12-18
    • 2019-10-18
    • 1970-01-01
    相关资源
    最近更新 更多