How do you add a JToken to an JObject?(如何将 JToken 添加到 JObject?)
问题描述
我正在尝试使用 JSON.Net 将一些文本中的 JSON 对象添加到现有 JSON 文件中.例如,如果我有如下 JSON 数据:
I'm trying to add a JSON object from some text to an existing JSON file using JSON.Net. For example if I have the JSON data as below:
{
"food": {
"fruit": {
"apple": {
"colour": "red",
"size": "small"
},
"orange": {
"colour": "orange",
"size": "large"
}
}
}
}
我一直在尝试这样做:
var foodJsonObj = JObject.Parse(jsonText);
var bananaJson = JObject.Parse(@"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}}");
var bananaToken = bananaJson as JToken;
foodJsonObj["food"]["fruit"]["orange"].AddAfterSelf(bananaToken);
但这给出了错误:Newtonsoft.Json.Linq.JProperty cannot have multiple values."
我实际上尝试了几种不同的方法,但似乎无处可去.在我的示例中,我真正想做的是将新项目添加到水果"中.请让我知道是否有更好的方法或更简单的库来使用.
I've actually tried a few different ways but can't seem to get anywhere. In my example what I really want to do is add the new item to "fruit". Please let me know if there is a better way of doing this or a simpler library to use.
推荐答案
我想你对 JSON.Net 中什么可以容纳什么感到困惑.
I think you're getting confused about what can hold what in JSON.Net.
JToken是任何类型的 JSON 值的通用表示.它可以是字符串、对象、数组、属性等.JProperty是与名称配对的单个JToken值.只能添加到一个JObject,它的值不能是另一个JProperty.JObject是JProperties的集合.它不能直接持有任何其他类型的JToken.
- A
JTokenis a generic representation of a JSON value of any kind. It could be a string, object, array, property, etc. - A
JPropertyis a singleJTokenvalue paired with a name. It can only be added to aJObject, and its value cannot be anotherJProperty. - A
JObjectis a collection ofJProperties. It cannot hold any other kind ofJTokendirectly.
在您的代码中,您尝试将 JObject(包含香蕉"数据的那个)添加到已经有一个 JProperty(橙色")值(包含 {"colour":"orange","size":"large"} 的 JObject).如您所见,这将导致错误.
In your code, you are attempting to add a JObject (the one containing the "banana" data) to a JProperty ("orange") which already has a value (a JObject containing {"colour":"orange","size":"large"}). As you saw, this will result in an error.
您真正想要做的是将一个名为banana"的JProperty 添加到包含其他水果JProperties 的JObject.这是修改后的代码:
What you really want to do is add a JProperty called "banana" to the JObject which contains the other fruit JProperties. Here is the revised code:
JObject foodJsonObj = JObject.Parse(jsonText);
JObject fruits = foodJsonObj["food"]["fruit"] as JObject;
fruits.Add("banana", JObject.Parse(@"{""colour"":""yellow"",""size"":""medium""}"));
这篇关于如何将 JToken 添加到 JObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 JToken 添加到 JObject?
基础教程推荐
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 将数据集转换为列表 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 如果条件可以为空 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 获取C#保存对话框的文件路径 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
