C# 如何使用newton软件仅序列化类的复杂类型属性中的特定值

C# 如何使用newton软件仅序列化类的复杂类型属性中的特定值,c#,json,.net,json.net,jsonserializer,C#,Json,.net,Json.net,Jsonserializer,我有一个具有多个属性的类,其中一些属性是复杂类型,而它本身具有多个其他属性,我不想对所有这些不需要的属性使用JsonIgnore注释,只想从某个复杂类型中获得一个要序列化的属性 例如,我有3门课 class Organization { public Int32 ID {get; set;} public string Name {get; set;} public Geography Location {get; set;} public Employee Ar

我有一个具有多个属性的类,其中一些属性是复杂类型,而它本身具有多个其他属性,我不想对所有这些不需要的属性使用
JsonIgnore
注释,只想从某个复杂类型中获得一个要序列化的属性

例如,我有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;}
}
在这里,我想序列化
组织
类对象,该对象应该只包括地理位置中的'Country'和相应位置和区域头属性的Employee中的'EmpID',我希望使用NewtonSoft库中的
JsonConvert.SerializeObject
方法得到json字符串输出,如下所示

{
   "ID":1,
   "Name":"Sales",
   "Location":"India",
   "AreaHead":5464
}
这是否可以使用DefaultContractResolver实现

合同解析程序

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

}
公共类DynamicContractResolver:DefaultContractResolver
{
私有只读InfoProperty[]\u jasonProperties;
公共DynamicContractResolver(参数InfoProperty[]包括验证属性)
{
_JasonProperties=用于验证的IncludeProperty;
}
受保护的重写JsonContract CreateContract(类型objectType)
{
if(typeof(TFDisplay).IsAssignableFrom(objectType))
{
var contract=this.CreateObjectContract(objectType);
contract.Converter=null;//还将转换器设置为null,以防止无限递归。
退货合同;
}
返回base.CreateContract(objectType);
}
受保护的重写IList CreateProperties(类型类型,MemberSerialization MemberSerialization)
{
IList properties=base.CreateProperties(类型、成员序列化);
if(_jasonproperties!=null&&u jasonproperties.Length>0)
{
if(_jasonproperties.Any(o=>(o.PropertyContainer??type)==type))
{
properties=properties.Where(p=>\u jasonproperties.Any(o=>(o.PropertyContainer??type)==type&&o.PropertyName==p.PropertyName)).ToList();
}
}
归还财产;
}
公共类InfoProperty
{
公共InfoProperty(字符串propertyName)
{
this.PropertyName=PropertyName;
}
公共InfoProperty(){}
公共InfoProperty(类型propertyContainer,字符串propertyName)
{
this.PropertyContainer=PropertyContainer;
this.PropertyName=PropertyName;
}
公共类型PropertyContainer{get;set;}
公共字符串PropertyName{get;set;}
}
}
您可以从给定的
组织
类创建一个只包含所需属性的,并使用
JsonConvert.SerializeObject()
函数获取所需的JSON字符串

  • 从现有组织实例创建匿名类型

    var input = new {
     ID = organization.ID,
     Name =  organization.Name,
     Location = organization.Location.Country,
     AreaHead = organization.AreaHead.EmpID 
    
    }
    
  • 现在使用NewtonSoft.Json库

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

  • 使用方法,


    联机尝试:

    因为您正在谈论选择性加入序列化(您只想序列化特定值),所以最简单的方法是序列化匿名类型,例如
    new{organization.ID,organization.Name,Location=organization.Location.Country,AreaHead=organization.AreaHead.EmpID}
    我建议你再问一个问题,而不是把你的问题改写成另一个问题。你已经得到了你现有问题的两个正确答案,你不应该重写它来使它们无效。见:和。
    //Here input is an anonymous object variable declared in above section
    var result = JObject.FromObject(input).ToString()
    Console.WriteLine(result);