C
C#2y ago
LPeter1997

❔ OneOf deserializer for Newtonsoft JSON

I have a lot of data-contracts generated from code, which utilizes OneOf<...> (https://github.com/mcintyre321/OneOf) quite a lot because of the provided schema. There are cases where some of the alternatives are primitives, like OneOf<Int32, String> or OneOf<Boolean, FullCapabilities>, but there are also cases where everything is some object, like OneOf<NotebookDocumentSyncOptions, NotebookDocumentSyncRegistrationOptions>. Important, I can't change the schema, so I can't introduce custom type-information fields. This is a schema given by VS Code I must follow. Writing the serializer part is easy enough:
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value is null)
{
serializer.Serialize(writer, null);
return;
}
var oneOf = (IOneOf)value;
serializer.Serialize(writer, oneOf.Value);
}
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value is null)
{
serializer.Serialize(writer, null);
return;
}
var oneOf = (IOneOf)value;
serializer.Serialize(writer, oneOf.Value);
}
Now writing the deserializer should be technically possible. One could go through the generic args of the type to be deserialized and find what properties definitely discriminate for a given alternative. Has this been written before for OneOf or any of its alternatives? If possible, I'd like to avoid writing my own, possibly buggy and slow version of this.
1 Reply
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server