我有以下属性
{
"bad":
{
"Login": "someLogin",
"Street": "someStreet",
"House": "1",
"Flat": "0",
"LastIndication":
[
"230",
"236"
],
"CurrentIndication":
[
"263",
"273"
],
"Photo":
[
null,
null
]
}
}
如何将这个从“坏”重命名为“好”,例如。是的,我看到了Abi Bellamkonda的扩展方法
public static class NewtonsoftExtensions
{
public static void Rename(this JToken token, string newName)
{
var parent = token.Parent;
if (parent == null)
throw new InvalidOperationException("The parent is missing.");
var newToken = new JProperty(newName, token);
parent.Replace(newToken);
}
}
但它得到了这个例外
无法将Newtonsoft.Json.Linq.JProperty添加到 Newtonsoft.Json.Linq.JProperty。
答案 0 :(得分:4)
有些违反直觉,该扩展方法假定您传递给它的token
是JProperty
的值,而不是JProperty
本身。据推测,这是为了方便使用方括号语法:
JObject jo = JObject.Parse(json);
jo["bad"].Rename("good");
如果你有对该属性的引用,如果你在属性的Value
上调用它,你仍然可以使用该扩展方法:
JObject jo = JObject.Parse(json);
JProperty prop = jo.Property("bad");
prop.Value.Rename("good");
然而,这使代码看起来令人困惑。最好改进扩展方法,以便在两种情况下都能正常工作:
public static void Rename(this JToken token, string newName)
{
if (token == null)
throw new ArgumentNullException("token", "Cannot rename a null token");
JProperty property;
if (token.Type == JTokenType.Property)
{
if (token.Parent == null)
throw new InvalidOperationException("Cannot rename a property with no parent");
property = (JProperty)token;
}
else
{
if (token.Parent == null || token.Parent.Type != JTokenType.Property)
throw new InvalidOperationException("This token's parent is not a JProperty; cannot rename");
property = (JProperty)token.Parent;
}
var newProperty = new JProperty(newName, property.Value);
property.Replace(newProperty);
}
然后你可以这样做:
JObject jo = JObject.Parse(json);
jo.Property("bad").Rename("good"); // works with property reference
jo["good"].Rename("better"); // also works with square bracket syntax