Skip to content

AnyOf.System.Text.Json

Stef Heyenrath edited this page Sep 21, 2021 · 2 revisions

AnyOf.System.Text.Json

This package contains a AnyOfJsonConverter which can:

  • Deserialize a json to a C# class which contains a AnyOf<TFirst, ...> class
  • Serializie a C# class which contains a AnyOf<TFirst, ...> class to a valid json

Usage

C# Classes

public class Mapping
{
    public string Id { get; set; }

    public AnyOf<ResponseAnyOfFirst, ResponseAnyOfSecond, ResponseAnyOfThird> Response { get; set; }
}
public class ResponseAnyOfFirst
{
    public int Median { get; set; }

    public double Sigma { get; set; }

    public string Type { get; set; }
}
public class ResponseAnyOfSecond
{
    public int Lower { get; set; }

    public string Type { get; set; }

    public int Upper { get; set; }
}
public class ResponseAnyOfThird
{
    public int Status { get; set; }

    public string StatusMessage { get; set; }
}

JSON Option 1

mappingAsJson is:

{
  "Id": null,
  "Response": {
    "Status": 0,
    "StatusMessage": "test"
  }
}

Deserialize

var options = new JsonSerializerOptions();
options.Converters.Add(new AnyOfJsonConverter());

var mapping = JsonSerializer.Deserialize<Mapping>(mappingAsJson, options);

Serialize

var mapping = new Mapping
{
    Id = "123",
    Response = new ResponseAnyOfThird
    {
        Status = 404,
        StatusMessage = "Not Found",
        Body = "x"
    }
};

var options = new JsonSerializerOptions
{
    WriteIndented = true
};
options.Converters.Add(new AnyOfJsonConverter());

var mappingAsJson = JsonSerializer.Serialize(mapping, options);
Clone this wiki locally