【问题标题】:Rename JProperty in json.net在 json.net 中重命名 JProperty
【发布时间】:2018-04-26 07:47:52
【问题描述】:

我有以下属性

{
  "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.

【问题讨论】:

  • 看起来很酷,但它不起作用。在这个例子中,root obj 是它的 JObject。但就我而言,我有一些 JProperty 数组并在 foreach 中使用它们,就像 JArray curLog = JArray.Parse(currentJsonLog); curLog.Children<JObject>().ToList() .ForEach(o => o.Properties().ToList() .ForEach(p => { if (p.Name == "bad") { //p.ChangeKey("newName");}

标签: c# .net json.net


【解决方案1】:

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

小提琴:https://dotnetfiddle.net/RSIdfx

【讨论】:

  • 请注意new JProperty(newName, property.Value); 将导致property.Value 层次结构被克隆,因为JToken 只能有一个父级;见dotnetfiddle.net/R0h6wE。您可能想像这样预先将property.Value 设置为nulldotnetfiddle.net/u5aUnj
  • @dbc 谢谢,我已经更新了我的答案以纳入您的建议。
  • 很棒的扩展方法!像魅力一样工作
猜你喜欢
  • 2012-05-19
  • 1970-01-01
  • 2012-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-15
  • 2019-06-12
  • 1970-01-01
相关资源
最近更新 更多