Search code examples
c#asp.netjson.netdeserialization

Deserialize JSON objects do different class names


I am using System.Text.Json to deserialize objects from an external API call in C#. I have created the classes for the data and is very straight-forward.

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

The default name for DocumentListRoot was Root and I changed that with no issues. What I would like to do is to change the name of LevelDocumentList to a different name. I have seen several posts here but they are pertaining to changing attribute names, not class names. I did try parsing the JSON string and renaming the class there, and it works, but that seems like a hack. I would like to know if there is a way while deserializing, to change the names of the classes.

Thank you


Solution

  • Then you can change your class name as you need. Since deserialization only cares about names of properties as @ gunr2171 said. You can change your class name accordingly as well as work around but not a hacky way of doing it.

    Refer to the code below:

    public class DocumentListRoot
    {        
        public List<MyLevelDocumentList> LevelDocumentList { get; set; }  // New class name
        public string FileNumber { get; set; }
        // other remaining properties
    }
    
    public class MyLevelDocumentList // New class name
    {
        public string FolderName { get; set; }
        public string FolderAutomationId { get; set; }
        public string DocumentTypeName { get; set; }
        public List<MyAttribute> Attributes { get; set; } // refer the new class name 
        // define other properties as usual 
    }
    
    public class MyAttribute // New class you want
    {
        public string name { get; set; }
        public string value { get; set; }
    }