问题描述
我想使用字符串路径将新的JProperty添加到JSON对象.我正在检索现有路径,然后在其附近添加一个新值.似乎无论我如何选择令牌,还是无论我调用哪种Add方法(最相关的是AddAfterSelf)还是作为新值提供的东西,都会收到异常:
I want to add a new JProperty to a JSON object using a string path.I'm retrieving an existing path and then adding a new value proximal to it.It seems no matter how I select a token, or no matter what Add method I call (most relevant is AddAfterSelf) or what I supply as a new value, I receive the exception:
您会在这里看到失败: https://dotnetfiddle.net/mnvmOI
You can see this failing here: https://dotnetfiddle.net/mnvmOI
在这种情况下为什么不能添加JProperty?
Why can't I add a JProperty in this situation?
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"));
}
}
推荐答案
引发异常的原因是 SelectToken()
返回属性的JValue
,而不是 JProperty
本身.具体来说,它将返回名称为"another"
的JProperty
所拥有的JValue
.如果您这样做,可以看到以下内容:
The reason that the exception is thrown is that SelectToken()
returns the property's JValue
not the JProperty
itself. Specifically, it returns a JValue
owned by the JProperty
with name "another"
. You can see this if you do:
Console.WriteLine("Result type: {0}; result parent type: {1}", result.GetType(), result.Parent.GetType());
会导致
Result type: Newtonsoft.Json.Linq.JValue; result parent type: Newtonsoft.Json.Linq.JProperty
如果进一步将对象类型从JToken
层次结构的顶部打印到SelectToken()
返回的值,您将看到JValue
标记包含在JProperty
标记内:
And if you further print the object types from the top of the JToken
hierarchy to the value returned by SelectToken()
, you will see the JValue
tokens contained inside the JProperty
tokens:
Depth: 0, Type: JObject
Depth: 1, Type: JProperty: deeper
Depth: 2, Type: JObject
Depth: 3, Type: JProperty: another
Depth: 4, Type: JValue: value
Json.NET文档还指示SelectToken()
返回所选属性的值:
The Json.NET documentation also indicates that SelectToken()
returns the selected property's value:
string name = (string)o.SelectToken("Manufacturers[0].Name");
Console.WriteLine(name);
// Acme Co
由于JProperty
不能有多个值,因此当您尝试在层次结构中的值之后立即添加JProperty
时,您尝试将其添加为其父级JProperty
的子级,例外.
Since a JProperty
cannot have more than one value, when you try to add a JProperty
immediately after the value in the hierarchy, you are trying to add it as a child of its parent JProperty
, which throws the exception.
相反,将其添加到父级的父级中:
Instead, add it to parent's parent:
test.SelectToken("deeper.another").Parent.AddAfterSelf(new JProperty("new name","new value"));
示例小提琴显示以上所有内容.
Sample fiddle showing all of the above.
这篇关于与SelectToken一起使用时,为什么AddAfterSelf返回"JProperty不能有多个值"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!