我想使用字符串路径将新的JProperty添加到JSON对象。我正在检索现有路径,然后在其附近添加一个新值。似乎无论我如何选择令牌,或者无论我调用哪种Add方法(最相关的是AddAfterSelf)或作为新值提供的东西,我都会收到异常:
运行时异常(第9行):Newtonsoft.Json.Linq.JProperty不能具有多个值。
您可以在这里看到失败:https : //dotnetfiddle.net/mnvmOI
在这种情况下为什么不能添加JProperty?
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
JObject test = JObject.Parse("{\"test\":123,\"deeper\":{\"another\":\"value\"}}");
test.SelectToken("deeper.another").AddAfterSelf(new JProperty("new name","new value"));
}
}
Run Code Online (Sandbox Code Playgroud)
引发异常的原因是SelectToken()
返回属性的JValue
不是JProperty
本身。具体来说,它将返回一个名称为的JValue
所有者。如果您这样做,则可以看到此信息:JProperty
"another"
Console.WriteLine("Result type: {0}; result parent type: {1}", result.GetType(), result.Parent.GetType());
Run Code Online (Sandbox Code Playgroud)
导致
Result type: Newtonsoft.Json.Linq.JValue; result parent type: Newtonsoft.Json.Linq.JProperty
Run Code Online (Sandbox Code Playgroud)
而且,如果您进一步从JToken
层次结构的顶部打印对象类型到所返回的值SelectToken()
,您将看到这些JValue
令牌中包含的JProperty
令牌:
Depth: 0, Type: JObject
Depth: 1, Type: JProperty: deeper
Depth: 2, Type: JObject
Depth: 3, Type: JProperty: another
Depth: 4, Type: JValue: value
Run Code Online (Sandbox Code Playgroud)
该Json.NET文档还指出,SelectToken()
返回所选属性的值:
Run Code Online (Sandbox Code Playgroud)string name = (string)o.SelectToken("Manufacturers[0].Name"); Console.WriteLine(name); // Acme Co
由于a JProperty
不能有多个值,因此当您尝试JProperty
在层次结构中的值后立即添加一个数字时,您尝试将其作为其父项的子项添加JProperty
,这会引发异常。
而是将其添加到父级的父级中:
test.SelectToken("deeper.another").Parent.AddAfterSelf(new JProperty("new name","new value"));
Run Code Online (Sandbox Code Playgroud)
显示以上所有内容的样本小提琴。
归档时间: |
|
查看次数: |
1984 次 |
最近记录: |