Json in C#

C# provides built-in support for JSON encoding and decoding, including to and from built-in and custom data types. We’ll use the System.Text.Json namespace for JSON operations.

First, let’s define our custom types:

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

public class Response1
{
    public int Page { get; set; }
    public string[] Fruits { get; set; }
}

public class Response2
{
    [JsonPropertyName("page")]
    public int Page { get; set; }

    [JsonPropertyName("fruits")]
    public string[] Fruits { get; set; }
}

class Program
{
    static void Main()
    {
        // Encoding basic data types to JSON strings
        Console.WriteLine(JsonSerializer.Serialize(true));
        Console.WriteLine(JsonSerializer.Serialize(1));
        Console.WriteLine(JsonSerializer.Serialize(2.34));
        Console.WriteLine(JsonSerializer.Serialize("gopher"));

        // Encoding slices and dictionaries
        Console.WriteLine(JsonSerializer.Serialize(new[] { "apple", "peach", "pear" }));
        Console.WriteLine(JsonSerializer.Serialize(new Dictionary<string, int> { { "apple", 5 }, { "lettuce", 7 } }));

        // Encoding custom types
        var res1 = new Response1
        {
            Page = 1,
            Fruits = new[] { "apple", "peach", "pear" }
        };
        Console.WriteLine(JsonSerializer.Serialize(res1));

        var res2 = new Response2
        {
            Page = 1,
            Fruits = new[] { "apple", "peach", "pear" }
        };
        Console.WriteLine(JsonSerializer.Serialize(res2));

        // Decoding JSON data
        string jsonString = @"{""num"":6.13,""strs"":[""a"",""b""]}";
        using JsonDocument doc = JsonDocument.Parse(jsonString);
        JsonElement root = doc.RootElement;

        double num = root.GetProperty("num").GetDouble();
        Console.WriteLine(num);

        string str1 = root.GetProperty("strs")[0].GetString();
        Console.WriteLine(str1);

        // Decoding JSON into custom types
        string jsonResponse = @"{""page"": 1, ""fruits"": [""apple"", ""peach""]}";
        Response2 response = JsonSerializer.Deserialize<Response2>(jsonResponse);
        Console.WriteLine($"{{Page:{response.Page}, Fruits:[{string.Join(", ", response.Fruits)}]}}");
        Console.WriteLine(response.Fruits[0]);

        // Streaming JSON directly to console output
        using (var stream = Console.OpenStandardOutput())
        {
            var options = new JsonSerializerOptions { WriteIndented = true };
            JsonSerializer.Serialize(stream, new Dictionary<string, int> { { "apple", 5 }, { "lettuce", 7 } }, options);
        }
    }
}

This C# code demonstrates JSON encoding and decoding using the System.Text.Json namespace. It covers:

  1. Encoding basic data types to JSON strings.
  2. Encoding arrays and dictionaries to JSON.
  3. Encoding custom types to JSON.
  4. Decoding JSON data into generic C# objects.
  5. Decoding JSON into custom C# types.
  6. Streaming JSON directly to console output.

The JsonPropertyName attribute is used to customize the JSON property names, similar to struct tags in the original example.

To run this program, save it as JsonExample.cs and compile it using the C# compiler:

$ csc JsonExample.cs
$ JsonExample.exe

This will produce output similar to the original example, demonstrating various JSON operations in C#.

For more information on JSON in C#, refer to the System.Text.Json documentation.