【问题标题】:Remove property based on path when serializing to json序列化为json时根据路径删除属性
【发布时间】:2018-11-08 05:43:28
【问题描述】:

我想在序列化对象时删除基于字符串列表的属性。我尝试使用DefaultContractResolver,但它提供了property.PropertyName,并且与路径或父对象无关:

public class Foo {
     public Bar Bar {get;set;}
}

public class Bar {
     public int MyProperty { get;set; }
     public int MyProperty2 { get;set; }
     public int MyProperty3 { get;set; }
}

var remove = new List<string> {
     "Foo.Bar.MyProperty"
}

Foo.Bar.MyProperty 不会被序列化的方式序列化该对象的最佳方法是什么?

【问题讨论】:

标签: json.net


【解决方案1】:

我认为 json.net 库对此用例没有任何帮助,但您可以手动完成:

JObject result = JObject.Parse(JsonConvert.SerializeObject(myObject));
foreach (var entry in remove)
{
    JObject current = result;
    var propertyChain = entry.Split(".").ToList();
    for(var i = 0; i < propertyChain.Count; i++)
    {
        if (i < propertyChain.Count - 1)
        {
            current = (JObject) current[propertyChain[i]];
        }
        else 
        {
            current.Remove(propertyChain[i]);
        }
    }
}
var myJson = result.ToString();

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多