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 值
基础教程推荐
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- WPF 模态进度窗口 2022-01-01
