How do you Add or Update a JProperty Value in a JObject(如何在 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 值
基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 XML 转换为通用列表 2022-01-01