在 C# 中使用可变子根名称反序列化 JSON 文件

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

我正在使用 System.Text.Json 包中的 JsonSerializer.Deserialize<>(json) 方法在 C# 中读取 JSON 文件。 JSON 文件包含以下节点文本类:

"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"
        }
    },

我应该如何在我的 C# 项目中定义类结构,因为我们在 textClasses 节点下有可变的子根名称(callout、title、header、label)?

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

使用Convert Json to C# Classes Online中的转换工具给出以下结构:

public class Callout
{
    public int fontSize { get; set; }
    public string fontFace { get; set; }
    public string color { get; set; }
}

public class Header
{
    public int fontSize { get; set; }
    public string fontFace { get; set; }
    public string color { get; set; }
}

public class Label
{
    public int fontSize { get; set; }
    public string fontFace { get; set; }
    public string color { get; set; }
}

public class Root
{
    public TextClasses textClasses { get; set; }
}

public class TextClasses
{
    public Callout callout { get; set; }
    public Title title { get; set; }
    public Header header { get; set; }
    public Label label { get; set; }
}

public class Title
{
    public int fontSize { get; set; }
    public string fontFace { get; set; }
    public string color { get; set; }
}

我也有一种感觉,这些天你可以在 Microsoft Visual Studio 中做类似的事情。

© www.soinside.com 2019 - 2024. All rights reserved.