【问题标题】:How to format and validate JSON in anonymous type using C# properly?如何正确使用 C# 格式化和验证匿名类型的 JSON?
【发布时间】:2022-11-04 16:01:04
【问题描述】:

我使用 Chart.js 和 Blazor wasm 制作图表。因此,我需要一个 JSON 配置对象作为匿名类型。像这样:

var config = new
    {
        Type = "line",
        Options = new
        {
            Responsive = true,
        },
        Data = new
        {
            Labels = Labels,
            DataSets = new object[]
            {
                new
                {
                    Label = "Line 1",
                    Data = Values,
                    Fill = false,
                    BorderColor = "red",
                    Tension = 0.1
                }
            }
        },
    };

这只是一个简单的例子,我的配置文件会增长很多。因此,通过设置或缺少逗号来出错是最有可能的,并且很难找到错误。 Visual Studio 也无法正确格式化。有时需要重新启动才能正确格式化。

有没有办法改善这一点?如何验证配置对象?

【问题讨论】:

    标签: c# json chart.js blazor blazor-webassembly


    【解决方案1】:

    使用 Newtonsoft 包,您可以将 json 转换为 [JObject],然后访问属性。

    也可以为反序列化创建自定义处理程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-25
      • 1970-01-01
      • 2021-04-24
      • 1970-01-01
      • 2010-09-24
      • 2015-01-22
      • 2014-06-14
      • 1970-01-01
      相关资源
      最近更新 更多