-1

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

}
Neeraj Kumar Gupta
  • 2,157
  • 7
  • 30
  • 58
  • Since you are talking about opt-in serialization (you want to serialize only specific values) easiest is to serialize an anonymous type such as `new { organization.ID, organization.Name, Location = organization.Location.Country, AreaHead = organization.AreaHead.EmpID }` – dbc May 27 '21 at 17:17
  • I'd suggest that you ask another question rather than rewriting your question to ask something different. You've already gotten two correct answers to your existing question, you shouldn't rewrite it to invalidate them. See: [How much change to the question is too much?](https://meta.stackoverflow.com/q/290297) and [Can I ask only one question per post?](https://meta.stackexchange.com/q/222735). – dbc May 27 '21 at 19:06

1 Answers1

1

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

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44