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

     2023-03-31     206

关键词:

【中文标题】如何使用牛顿软从类的复杂类型属性中仅序列化特定值【英文标题】:how to serialize only specific value from complex type property of class using newton soft 【发布时间】:2021-08-15 23:38:56 【问题描述】:

我有一个具有多个属性的类,其中一些属性是一种复杂类型,而它本身具有多个其他属性,我不想在所有这些不需要的属性上使用 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;

在这里我想序列化 Organization 类对象,它应该只包括来自 Geography 的“Country”和来自 Employee 的各自 Location 和 AreaHead 属性的“EmpID”,我期望的 json 字符串输出如下使用JsonConvert.SerializeObject NewtonSoft 库中的方法。


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

这可以使用 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; 
    


【问题讨论】:

既然您在谈论选择加入序列化(您只想序列化特定值),最简单的方法是序列化匿名类型,例如 new organization.ID, organization.Name, Location = organization.Location.Country, AreaHead = organization.AreaHead.EmpID 我建议您问另一个问题,而不是重写您的问题以提出不同的问题。您已经得到了对现有问题的两个正确答案,您不应该重写它以使它们无效。请参阅:How much change to the question is too much? 和 Can I ask only one question per post?。 【参考方案1】:

您可以从给定的Organization 类创建一个anonymous object 仅具有必需的属性,并使用JsonConvert.SerializeObject() 函数获取所需的 JSON 字符串

    从现有的组织实例创建一个匿名类型。

    var input = new 
     ID = organization.ID,
     Name =  organization.Name,
     Location = organization.Location.Country,
     AreaHead = organization.AreaHead.EmpID 
    
    
    

    现在Serialize this object 使用 NewtonSoft.Json 库,

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

使用JObject.FromObject()方法,

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

在线试用:.NET FIDDLE

【讨论】:

spring - 从类的静态字段中的属性文件中读取属性值

...随时更改它。但是当我在静态方法(作为实用程序类)中使用它时,问题是它 查看详情

jQuery - 从类的元素中获取属性值的列表

】jQuery-从类的元素中获取属性值的列表【英文标题】:jQuery-getalistofvaluesofanattributefromelementsofaclass【发布时间】:2011-02-1418:58:35【问题描述】:我有一个类.object,它有一个名为level的属性。我想在页面上获取level的所有不同值的... 查看详情

如何在 Visual Studio 代码中仅搜索特定文件类型?

】如何在VisualStudio代码中仅搜索特定文件类型?【英文标题】:HowtosearchforjustaspecificfiletypeinVisualStudiocode?【发布时间】:2018-03-1707:22:38【问题描述】:在VisualStudio代码中,如何仅搜索特定的文件类型(即*.css或*.ts)?PS:我说的... 查看详情

如何将不同类型的子元素反序列化为基类型的列表/集合,这是相应类的属性

】如何将不同类型的子元素反序列化为基类型的列表/集合,这是相应类的属性【英文标题】:Howtodeserializechildelementsofdifferenttypesintolist/collectionofbasetypewhichisapropertyofthecorrespondingclass【发布时间】:2020-11-0303:18:11【问题描述】:我... 查看详情

如何从类属性 TypeScript 中侦听值更改 - Angular

】如何从类属性TypeScript中侦听值更改-Angular【英文标题】:HowtolistenforvaluechangesfromclasspropertyTypeScript-Angular【发布时间】:2018-09-0804:28:44【问题描述】:在AngularJS中,我们可以使用$watch、$digest...监听变量变化,而新版本的Angular(5,... 查看详情

如何从类路径加载属性文件? [关闭]

】如何从类路径加载属性文件?[关闭]【英文标题】:Howtoloadpropertyfilefromclasspath?[closed]【发布时间】:2012-08-1500:23:55【问题描述】:getResourceAsStream()是java.lang.Class类的方法。此方法在类路径中找到具有给定名称的资源。实际上这... 查看详情

如何从选定行的网格面板中仅获取特定值

】如何从选定行的网格面板中仅获取特定值【英文标题】:HowtoGetonlyParticularvaluefromagridpanelonselectedRow【发布时间】:2012-03-1006:16:37【问题描述】:我的网格面板如下<ext:GridPanelID="GridPanel1"runat="server"Height="300"Title="Title"><Colum... 查看详情

在 Python(tkinter)中从类的外部更改类的私有属性(标签)

...【发布时间】:2021-08-1307:26:29【问题描述】:我在Python中使用tkinter制作了一个GUI,我创建了一个名为“Window”的类来管理整个会话期间GUI中的所有创建、运行和更改。我不知 查看详情

NewtonSoft Json转换列表

...描述】:我有一个非常简单的结构,我想使用牛顿软Json序列化进行序列化。定义:publicenumSensorTypeTemperature,Flow,PressurepublicenumSensorLocationManifold,TopVessel,WaferStage[Jso 查看详情

序列化特定类型时如何使 JSON.Net 序列化程序调用 ToString()?

】序列化特定类型时如何使JSON.Net序列化程序调用ToString()?【英文标题】:HowtomakeJSON.NetserializertocallToString()whenserializingaparticulartype?【发布时间】:2014-04-1618:50:30【问题描述】:我正在使用Newtonsoft.Json序列化程序将C#类转换为JSON... 查看详情

如何使用具有类的通用类型的 ObjectMapper 反序列化 JsonString

】如何使用具有类的通用类型的ObjectMapper反序列化JsonString【英文标题】:HowtodeserializeJsonStringusingObjectMapperwithGenericTypeofaclass【发布时间】:2019-03-1711:54:56【问题描述】:假设我有一个模型类ResponseModel@Setter//Thisonenotworkingpublicclass... 查看详情

使用“类”数据类型时,如何指定类型以便只接受特定类的子类?

】使用“类”数据类型时,如何指定类型以便只接受特定类的子类?【英文标题】:Whenusingthe\'Class\'datatype,howcanIspecifythetypesoIonlyacceptsubclassofaspecificclass?【发布时间】:2015-03-2803:04:31【问题描述】:我有一个接受Class类型参数的... 查看详情

如何序列化 CustomLineCap 类的实例

】如何序列化CustomLineCap类的实例【英文标题】:HowtoserializeaninstanceoftheCustomLineCapclass【发布时间】:2012-02-2903:04:27【问题描述】:CustomLineCap没有应用SerializableAttribute。我想将这种类型的属性添加到当前正在使用BinaryFormatter进行... 查看详情

如何使用 Core Data 在 DB 中仅添加单个值?

】如何使用CoreData在DB中仅添加单个值?【英文标题】:HowtoaddonlysinglevalueinDBwithCoreData?【发布时间】:2013-07-1516:21:22【问题描述】:我正在尝试将uniquevalues添加到我的sqlite数据库中。我尝试在.xcdatamodeld中创建唯一属性,但没有成... 查看详情

如何找到具有特定“类型”属性值的 <script> 元素?

】如何找到具有特定“类型”属性值的<script>元素?【英文标题】:Howtofind<script>elementswithparticularvalueof"type"attribute?【发布时间】:2013-06-0318:10:58【问题描述】:假设在一个随机的HTML文档中有以下脚本标签:<sc... 查看详情

如何从混合数据类型数组中仅提取一个数据类型值?

】如何从混合数据类型数组中仅提取一个数据类型值?【英文标题】:HowcanIextractonlyonedatatypevaluesfromamixeddatatypearray?【发布时间】:2021-01-3101:47:41【问题描述】:我的数组列表中有4种不同的数据类型。这些特定于我的应用程序(... 查看详情

尝试反序列化 JSON 对象数组,其中对象具有数组作为属性。我可以将数组元素映射到类的特定属性吗?

】尝试反序列化JSON对象数组,其中对象具有数组作为属性。我可以将数组元素映射到类的特定属性吗?【英文标题】:TryingtodeserializeJSONobjectarraywheretheobjectshavearraysasproperties.CanImapthearrayelementstospecificpropertiesofaclass?【发布时间】... 查看详情

有没有办法禁止从类的实例向类添加属性?

】有没有办法禁止从类的实例向类添加属性?【英文标题】:Isthereawaytodisableaddingpropertiesintoaclassfromaninstanceoftheclass?【发布时间】:2012-01-2716:53:06【问题描述】:有没有办法禁止将properties从类的实例添加到类中。我的意思是:考... 查看详情