Home > Net >  How to format and validate JSON in anonymous type using C# properly?
How to format and validate JSON in anonymous type using C# properly?

Time:11-05

I working on a chart using Chart.js and Blazor wasm. Therefor I need a JSON configuration object as an anonymous type. Like this:

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

This is just a simple example, my config file will grow up a lot. So, making mistakes by setting or missing commas is most likely and it will be difficult to find the mistake. Also Visual Studio has problems to format this properly. Sometime a restart is required to get it properly formatted.

Is there a way to improve this? How can I validate the config object?

CodePudding user response:

Using Newtonsoft package you can cast the json to [JObject] and then access the properties.

It's also possible to create custom handlers for deserialization.

CodePudding user response:

Sebastians answer is the right one. Aditional I figured out the problem regarding to formatting the anonymous type in VS.

Visual Studio 2022 has a problem to format the anonymous type of JSON string in razor components view. Create the object in code behind will fix this problem.

  • Related