Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
892 views
in Technique[技术] by (71.8m points)

c# - How do you Add or Update a JProperty Value in a JObject

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.

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).

i.e.,

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

data
    .SetPropertyContent("str1", "test2")
    .SetPropertyContent("str3", "test3");

// {
//   "str1": "test2",
//   "str3": "test3"
// }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...