反序列化 JSON 对象执行不同的类名称

问题描述 投票:0回答:1

我正在使用 System.Text.Json 从 C# 中的外部 API 调用反序列化对象。 我已经为数据创建了类,非常简单。

    public class DocumentListRoot
    {
        public List<LevelDocumentList> LevelDocumentList { get; set; }
        public string FileNumber { get; set; }
        ... more properties
    }

    public class LevelDocumentList
    {
        public string FolderName { get; set; }
        public string FolderAutomationId { get; set; }
        public string DocumentTypeName { get; set; }
        public List<Attribute> Attributes { get; set; }
        ... more properties
    }

    public class Attribute
    {
        public string name { get; set; }
        public string value { get; set; }
    }

DocumentListRoot 的默认名称是 Root,我更改了它,没有出现任何问题。 我想做的是将 LevelDocumentList 的名称更改为不同的名称。 我在这里看到了几篇文章,但它们与更改属性名称有关,而不是与类名称有关。 我确实尝试解析 JSON 字符串并重命名那里的类,它有效,但这看起来像是一个 hack。 我想知道是否有办法在反序列化时更改类的名称。

谢谢你

c# asp.net json .net deserialization
1个回答
0
投票

您可以在类的属性之上使用

[JsonPropertyName]
操作过滤器或属性并进行反序列化。

请参考以下代码:

public class DocumentListRoot
{
    [JsonPropertyName("differentName")] // Change the property name in JSON
    public List<LevelDocumentList> LevelDocumentList { get; set; }
    public string FileNumber { get; set; }
    // other remaining properties
}

public class LevelDocumentList
{
    public string FolderName { get; set; }
    public string FolderAutomationId { get; set; }
    public string DocumentTypeName { get; set; }
    public List<Attribute> Attributes { get; set; }
    // define other properties as usual 
}
© www.soinside.com 2019 - 2024. All rights reserved.