【发布时间】:2021-05-11 04:59:33
【问题描述】:
我想替换 JObject 中的属性名称。我在网上搜索了一些解决方案。发现我们可以从 Newtonsoft 扩展重命名功能。
我也找到了扩展方法。重命名功能适用于问题中提到的 JObjects,但不适用于所有。
我的代码是这样的:
class Program
{
static void Main(string[] args)
{
JObject o = JObject.Parse(@"{
'Stores': [
'Lambton Quay',
'Willis Street'
],
'Manufacturers': [
{
'Name': 'Acme Co',
'Products': [
{
'Name': 'Anvil',
'Price': 50
}
]
},
{
'Name': 'Contoso',
'Products': [
{
'Name': 'Elbow Grease',
'Price': 99.95
},
{
'Name': 'Headlight Fluid',
'Price': 4
}
]
}
]
}");
o.Property("Name").Rename("LongName");
Console.WriteLine(o.ToString());
}
}
public static class NewtonsoftExtensions
{
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;
}
// Note: to avoid triggering a clone of the existing property's value,
// we need to save a reference to it and then null out property.Value
// before adding the value to the new JProperty.
// Thanks to @dbc for the suggestion.
var existingValue = property.Value;
property.Value = null;
var newProperty = new JProperty(newName, existingValue);
property.Replace(newProperty);
}
}
这给了我错误“无法重命名空指针”。
谁能告诉我我在这里做错了什么。非常感谢。
【问题讨论】: