Skip to content

Code first model for System.Text.Json #32005

@casperOne

Description

@casperOne

I am currently publishing libraries which utilize the System.Text.Json libraries for parsing JSON content from HTTP endpoints.

Assuming I have a library Ofl.Twitch, I like to publish three libraries:

Ofl.Twitch.Abstractions ➡ Contains interface definitions, as well as data models that the interface definitions rely on.
Ofl.Twitch ➡ Contains the implementation of the interfaces in Ofl.Twitch.Abstractions; contains a NuGet package reference to Ofl.Twitch.Abstractions.
Ofl.Twitch.Extensions ➡ Contains helper functions that are not tied to direct implementations in Ofl.Twitch; contains a NuGet package reference to Ofl.Twitch.Abstractions.

I find that the issue I'm facing with System.Text.Json is the same as what I faced with JSON.Net; there is not an easy way to customize the serialization/deserialization of the data models outside of the assembly that they are housed in.

This means that we have to establish and distribute a reference to System.Text.Json along with our abstractions, which is not ideal.

This could be circumvented somewhat by separating the attributes into another assembly, but I don't think this is the right approach.

Ideally, the abstractions package would not have a reference to anything that contributes to implementation. Additionally, we would have an API that we could use in the implementation assembly which would be able to take a code-first approach to defining how properties on a model would behave, a la Entity Framework's code-first approach.

Presumably, much of this is already implemented internally in the JsonSerializer (and other contributing) class(es), it's just a matter of exposing it.

Granted, we could achieve this with a JsonConverter much in the same way that is recommended to handle polymorphism:

https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to#converter-samples-for-common-scenarios

IMO, this is a bit unwieldy, and a little too close to the metal, when in reality, we may need to just register a bunch of properties, hand tweaking how a few of them are serialized.

I suspect a mechanism, if exposed, would be exposed through the JsonSerializerOptions class, allowing us to set where the builder for a type is.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions