https://github.com/rmja/polyjson
Attribute based, polymorphic support for System.Text.Json.
https://github.com/rmja/polyjson
json polymorphism system-text-json
Last synced: 6 months ago
JSON representation
Attribute based, polymorphic support for System.Text.Json.
- Host: GitHub
- URL: https://github.com/rmja/polyjson
- Owner: rmja
- Created: 2021-12-17T11:35:36.000Z (about 4 years ago)
- Default Branch: master
- Last Pushed: 2023-12-12T05:27:46.000Z (about 2 years ago)
- Last Synced: 2024-04-26T22:42:17.275Z (over 1 year ago)
- Topics: json, polymorphism, system-text-json
- Language: C#
- Homepage:
- Size: 36.1 KB
- Stars: 12
- Watchers: 1
- Forks: 2
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# PolyJson
Attribute based, polymorphic support for System.Text.Json (and optionally Newtonsoft.Json). It supports both serialization and deserialization and is reasonably fast.
## Nuget Packages
| Package name | Description | Badge |
|-----------------------------------|-------------------------------|-------|
| `PolyJson` | Basic types and System.Text.Json support | [](https://www.nuget.org/packages/PolyJson) |
| `PolyJson.NewtonsoftJson` | Optional Newtonsoft.Json support | [](https://www.nuget.org/packages/PolyJson.NewtonsoftJson) |
## Usage
Decorate the base class with the `PolyJsonConverter` attribute and register the subtypes:
```C#
[PolyJsonConverter("_t")]
//[Newtonsoft.Json.JsonConverter(typeof(PolyJsonNewtonsoftJsonConverter))] // Optional
[PolyJsonConverter.SubType(typeof(Dog), "dog")]
[PolyJsonConverter.SubType(typeof(Cat), "cat")]
public abstract class Animal
{
[JsonPropertyName("_t")]
//[Newtonsoft.Json.JsonProperty("_t")] // Optional
public string Discriminator => DiscriminatorValue.Get(GetType());
public int Id { get; set; }
}
```
The `PolyJsonConverter` specifies the discriminator field, in this case `_t`. And all possible sub types are registered with their discriminator value.
The `Newtonsoft.Json` support is optional, but uses the same configured subtypes as that configured for `System.Text.Json`.
A sub type does not have any attributes and can for example be:
```C#
public class Dog : Animal
{
public bool CanBark { get; set; }
}
```