JSON Lark

Sheet 05 C# classes & records

JSON to C#

Paste JSON samples and get C# classes or records with JsonPropertyName or JsonProperty attributes and nullable reference types.

JSON

C#

#nullable enable

using System.Collections.Generic;
using System.Text.Json.Serialization;

namespace App.Models;

public class Root
{
    [JsonPropertyName("sku")]
    public string Sku { get; set; } = null!;

    [JsonPropertyName("title")]
    public string Title { get; set; } = null!;

    [JsonPropertyName("price")]
    public double Price { get; set; }

    [JsonPropertyName("inStock")]
    public bool InStock { get; set; }

    [JsonPropertyName("dimensions")]
    public Dimensions Dimensions { get; set; } = null!;

    [JsonPropertyName("variants")]
    public List<Variant> Variants { get; set; } = null!;
}

public class Dimensions
{
    [JsonPropertyName("width")]
    public double Width { get; set; }

    [JsonPropertyName("height")]
    public long Height { get; set; }

    [JsonPropertyName("unit")]
    public string Unit { get; set; } = null!;
}

public class Variant
{
    [JsonPropertyName("color")]
    public string Color { get; set; } = null!;

    [JsonPropertyName("stock")]
    public long Stock { get; set; }

    [JsonPropertyName("discontinued")]
    public bool? Discontinued { get; set; }
}

1 sample · 3 classes

General notes

How it works

Properties are PascalCase and keep their JSON names in attributes, so the classes work with the default serializer settings. Keys missing from some objects and values that can be null become nullable.

Classes, records, positional records
{ get; set; } properties, { get; init; } records, or records with a primary constructor whose attributes use the property: target.
Nullable reference types
Adds #nullable enable and string? where null is possible. Other reference properties get = null!;, or the required modifier when you tick "required members".
Attributes
System.Text.Json matches property names case-sensitively, so leave attributes on unless you configure a naming policy. Newtonsoft ignores case either way.
Names
A property named like its class gets a Value suffix, and names such as Equals are renamed so they do not hide object members.

Questions

How do I deserialize the result?

With System.Text.Json: JsonSerializer.Deserialize<Root>(json). With Newtonsoft: JsonConvert.DeserializeObject<Root>(json). When the JSON's top level is an array, the output starts with a comment naming the list type to use.

Why object for some properties?

Values that mix kinds, such as a number in one sample and a string in another, have no single C# type. They become object (a JsonElement with System.Text.Json) so nothing fails to deserialize.

Is my JSON uploaded?

No. The code is generated by JavaScript running in this tab, and nothing you paste leaves it. The site counts page views with Cloudflare Web Analytics, which sets no cookies and never receives what you paste.