简体   繁体   English

如何使用牛顿软件从 class 的复杂类型属性中仅序列化特定值

[英]how to serialize only specific value from complex type property of class using newton soft

I have a class with multiple properties where some of the properties is a complex type those it self having multiple other properties, I don't want to use JsonIgnore annotation over all those unwanted properties, looking way to get only one property to serialize from some complex type.我有一个 class 具有多个属性,其中一些属性是一种复杂类型,它本身具有多个其他属性,我不想在所有这些不需要的属性上使用JsonIgnore注释,寻找仅获取一个属性以从某些属性中序列化的方法复杂类型。

For example I have 3 classes例如我有 3 节课

class Organization
{
    public Int32 ID {get; set;}
    public string Name {get; set;}
    public Geography Location {get; set;}
    public Employee AreaHead {get; set;}
}

class Geography 
{
    public Int32 GeoID {get; set;}
    public string Country {get; set;}
    public string City {get; set;}
    public string State {get; set;}
}   

class Employee 
{
    public Int32 EmpID {get; set;}
    public string Name {get; set;}
    public DateTime DOB {get; set;}
    public string Gender {get; set;}
}

here I want to serialize the Organization class object, that should include only 'Country' from Geography and 'EmpID' from Employee for respective Location and AreaHead properties, the json string output I am expecting as below using JsonConvert.SerializeObject method from NewtonSoft library. here I want to serialize the Organization class object, that should include only 'Country' from Geography and 'EmpID' from Employee for respective Location and AreaHead properties, the json string output I am expecting as below using JsonConvert.SerializeObject method from NewtonSoft library.

{
   "ID":1,
   "Name":"Sales",
   "Location":"India",
   "AreaHead":5464
}

is this possible using DefaultContractResolver?这可以使用 DefaultContractResolver 吗?

ContractResolver合约解析器

public class DynamicContractResolver : DefaultContractResolver
{
    private readonly InfoProperty[] _jasonProperies;

    public DynamicContractResolver(params InfoProperty[] includePropertyForSerilization)
    {
        _jasonProperies = includePropertyForSerilization;
    }

    protected override JsonContract CreateContract(Type objectType)
    {
        if (typeof(TFDisplay).IsAssignableFrom(objectType))
        {
            var contract = this.CreateObjectContract(objectType);
            contract.Converter = null; // Also null out the converter to prevent infinite recursion.
            return contract;
        }
        return base.CreateContract(objectType);
    }


    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

        if (_jasonProperies != null && _jasonProperies.Length > 0)
        {
            if (_jasonProperies.Any(o => (o.PropertyContainer ?? type) == type))
            {
                properties = properties.Where(p => _jasonProperies.Any(o => (o.PropertyContainer ?? type) == type && o.PropertyName == p.PropertyName)).ToList();
            }

        }

        return properties;
    }

    public class InfoProperty
    {
        public InfoProperty(string propertyName)
        {
            this.PropertyName = propertyName;
        }
        public InfoProperty() { }
        public InfoProperty(Type propertyContainer, string propertyName)
        {
            this.PropertyContainer = propertyContainer;
            this.PropertyName = propertyName;
        }
        public Type PropertyContainer { get; set; }
        public string PropertyName { get; set; }
    }

}

You can create an anonymous object with only required properties from the given Organization class and use JsonConvert.SerializeObject() function to get the desired JSON string You can create an anonymous object with only required properties from the given Organization class and use JsonConvert.SerializeObject() function to get the desired JSON string

  1. Create an Anonymous type from the existing Organization instance.从现有的组织实例创建一个匿名类型。

     var input = new { ID = organization.ID, Name = organization.Name, Location = organization.Location.Country, AreaHead = organization.AreaHead.EmpID }
  2. Now Serialize this object using NewtonSoft.Json library,现在使用 NewtonSoft.Json 库序列化这个 object

     using Newtonsoft.Json; ... var result = JsonConvert.SerializeObject(input, Formatting.Indented); Console.WriteLine(result);

Using JObject.FromObject() method,使用JObject.FromObject()方法,

//Here input is an anonymous object variable declared in above section
var result = JObject.FromObject(input).ToString()
Console.WriteLine(result);

Try Online: .NET FIDDLE在线试用: .NET FIDDLE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM