Search code examples
c#json.netsystem.text.json

Deserialize JSON file in C# with variable sub root names


I'm working on a reading in a JSON file in C# using the JsonSerializer.Deserialize<>(json) method from the System.Text.Json package. The JSON file contains the following node textClasses:

"textClasses": {
        "callout": {
            "fontSize": 29,
            "fontFace": "Roboto Regular",
            "color": "#5158A7"
        },
        "title": {
            "fontSize": 12,
            "fontFace": "Roboto Regular",
            "color": "#5A6066"
        },
        "header": {
            "fontSize": 11,
            "fontFace": "Roboto Light",
            "color": "#5A6066"
        },
        "label": {
            "fontSize": 11,
            "fontFace": "Roboto Light",
            "color": "#5A6066"
        }
    },

How should I define the class structure in my C# project as we have variable sub root names (callout, title, header, label) under the textClasses node?


Solution

  • My suggestion would be to create classes which have all possibilities for your subroot names. Instances which don't have values for some of then would simply map nulls, zeroes or empty strings where the data is missing.

    public class TextClass
    {
        public CalloutBase Callout { get; set; }
        public CalloutBase Title { get; set; }
        public CalloutBase Header { get; set; }
        public CalloutBase Label { get; get; }
    }
    public class CalloutBase
    {
        public int FontSize { get; set; }
        public string FontFace { get; set; }
        public string Color { get; set; }
    }
    

    Your CalloutBase class defines the sub-members and the textClass reuses the CalloutBase for the callout, title, header and label.

    Any missing data would resolve to null.

    For example, the following Json would resolve to a TextClass object having valid data for callout, title and header, but a null value for label:

    "textClasses": {
            "callout": {
                "fontSize": 29,
                "fontFace": "Roboto Regular",
                "color": "#5158A7"
            },
            "title": {
                "fontSize": 12,
                "fontFace": "Roboto Regular",
                "color": "#5A6066"
            },
            "header": {
                "fontSize": 11,
                "fontFace": "Roboto Light",
                "color": "#5A6066"
            },
    }