gpt4 book ai didi

c# - 在 json.net 中重命名 JProperty

转载 作者:行者123 更新时间:2023-11-30 14:23:02 26 4
gpt4 key购买 nike

我有以下属性

{
"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);
}
}

但是它得到了这个异常(exception)

Can not add Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JProperty.

最佳答案

有点违反直觉,该扩展方法假设您传递给它的 tokenJPropertyvalue,而不是 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;
}

// 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);
}

然后你可以这样做:

JObject jo = JObject.Parse(json);
jo.Property("bad").Rename("good"); // works with property reference
jo["good"].Rename("better"); // also works with square bracket syntax

fiddle :https://dotnetfiddle.net/RSIdfx

关于c# - 在 json.net 中重命名 JProperty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47267542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com