Skip to content

AnyOf.Newtonsoft.Json

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

AnyOf.Newtonsoft.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 mapping = JsonConvert.DeserializeObject<Mapping>(mappingAsJson, new AnyOfJsonConverter());

Serialize

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

string mappingAsJson = JsonConvert.SerializeObject(mapping, Formatting.Indented, new AnyOfJsonConverter());