-
-
Notifications
You must be signed in to change notification settings - Fork 6
AnyOf.System.Text.Json
Stef Heyenrath edited this page Sep 21, 2021
·
2 revisions
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
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; }
}
mappingAsJson is:
{
"Id": null,
"Response": {
"Status": 0,
"StatusMessage": "test"
}
}
var options = new JsonSerializerOptions();
options.Converters.Add(new AnyOfJsonConverter());
var mapping = JsonSerializer.Deserialize<Mapping>(mappingAsJson, options);
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);