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?
2
Answers
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.
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:
as my understanding, its not a full json. so base on what i see your class would be (you can go and use online json to c# class converters) but always take it with grain of salt (it might create a duplicated classes.):
result would be