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

How do you Add or Update a JProperty Value in a JObject(如何在 JObject 中添加或更新 JProperty 值)

本文介绍了如何在 JObject 中添加或更新 JProperty 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用以下扩展方法来执行此任务,但似乎应该有一些现有的包含方法或扩展来执行此任务(或至少是其中的一个子集).如果 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";

查看 fiddle 了解更多详情

这篇关于如何在 JObject 中添加或更新 JProperty 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 JObject 中添加或更新 JProperty 值

基础教程推荐