简体   繁体   中英

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.

For example I have 3 classes

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.

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

is this possible using 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

  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,

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

Using JObject.FromObject() method,

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

Try Online: .NET FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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