All Projects → dmitry-bym → JsonKnownTypes

dmitry-bym / JsonKnownTypes

Licence: MIT license
Simple way to serialize and deserialize polymorphic types for Json.NET

Programming Languages

C#
18002 projects

Projects that are alternatives of or similar to JsonKnownTypes

MetaCPP
C++ Reflection & Serialization using Clang's LibTooling
Stars: ✭ 44 (+33.33%)
Mutual labels:  serialization
sirdez
Glorious Binary Serialization and Deserialization for TypeScript.
Stars: ✭ 20 (-39.39%)
Mutual labels:  serialization
laravel5-hal-json
Laravel 5 HAL+JSON API Transformer Package
Stars: ✭ 15 (-54.55%)
Mutual labels:  serialization
typical
Data interchange with algebraic data types.
Stars: ✭ 114 (+245.45%)
Mutual labels:  serialization
json-strictify
Safely serialize a value to JSON without unintended loss of data or going into an infinite loop due to circular references.
Stars: ✭ 14 (-57.58%)
Mutual labels:  serialization
use-query-string
🆙 A React hook that serializes state into the URL query string
Stars: ✭ 50 (+51.52%)
Mutual labels:  serialization
vue-query-builder
A Vue-Query-Builder
Stars: ✭ 71 (+115.15%)
Mutual labels:  serialization
persistity
A persistence framework for game developers
Stars: ✭ 34 (+3.03%)
Mutual labels:  serialization
HashStablePack
Serialization code generator for QUICK struct content comparison
Stars: ✭ 94 (+184.85%)
Mutual labels:  serialization
protoc-plugin
A protoc compiler plugin for Clojure applications
Stars: ✭ 28 (-15.15%)
Mutual labels:  serialization
ikeapack
Compact data serializer/packer written in Go, intended to produce a cross-language usable format.
Stars: ✭ 18 (-45.45%)
Mutual labels:  serialization
JsonFormatter
Easy, Fast and Lightweight Json Formatter. (Serializer and Deserializer)
Stars: ✭ 26 (-21.21%)
Mutual labels:  serialization
serialize-json
A serialize algorithm for JSON
Stars: ✭ 22 (-33.33%)
Mutual labels:  serialization
succinct-binary
Succinct binary serialization
Stars: ✭ 16 (-51.52%)
Mutual labels:  serialization
Deeplearning.ai-GAN-Specialization-Generative-Adversarial-Networks
This repository contains my full work and notes on Deeplearning.ai GAN Specialization (Generative Adversarial Networks)
Stars: ✭ 59 (+78.79%)
Mutual labels:  discriminator
FUPRAL
Fortran OO implementation of a generic container using an unlimited polymorphic class. Implementation of a resizable container array and a double linked list.
Stars: ✭ 18 (-45.45%)
Mutual labels:  polymorphic
tyson
A TypeScript serialization/deserialization library to convert objects to/from JSON
Stars: ✭ 25 (-24.24%)
Mutual labels:  serialization
jwEngine
A cross-platform C++<->lua server quick solution
Stars: ✭ 226 (+584.85%)
Mutual labels:  serialization
BinaryLove3
Simple C++ 20 Serialization Library that works out of the box with aggregate types!
Stars: ✭ 13 (-60.61%)
Mutual labels:  serialization
jsonrec
JSON parser/encoder "type spec"-based code-generator
Stars: ✭ 13 (-60.61%)
Mutual labels:  serialization

JsonKnownTypes .Net Standard

nuget downloads lisence

Buy Me A Coffee

Helps to serialize and deserialize polymorphic types. Adds discriminator to json.

Swashbuckle Support

To add discriminator to swagger(OpenAPI) scheme use this package JsonKnownTypes.Swashbuckle

Requirements

  • NET Standard 2.0 compatible project
  • Json.NET by Newtonsoft

Documentation

Getting started

The simplest way to use it is to add one attribute to base class or interface:

[JsonConverter(typeof(JsonKnownTypesConverter<BaseClass>))]
public class BaseClass
{
    public string Summary { get; set; }
}
  
public class ChildClass : BaseClass
{
    public string Detailed { get; set; }
}

Serialization and Deserialization:

var entityJson = JsonConvert.SerializeObject(entity);
var obj = DeserializeObject<BaseClass>(entityJson)

Json representation:

{ "Summary":"someValue", "$type":"BaseClass" }
{ "Summary":"someValue", "Detailed":"someValue", "$type":"ChildClass" }

Using with Interfaces or Abstract classes

Also, you can use it with interfaces or abstract classes:

Interface

[JsonConverter(typeof(JsonKnownTypesConverter<IInterface>))]
public interface IInterface  { ... }
 
public class ChildClass : IInterface  { ... }

Json representation:

{ ... "$type":"ChildClass" }

Abstract class

[JsonConverter(typeof(JsonKnownTypesConverter<AbstractClass>))]
public abstract class AbstractClass  { ... }
 
public class ChildClass : AbstractClass  { ... }

Json representation:

{ ... "$type":"ChildClass" }

JsonKnownType

If you need to add a custom discriminator use JsonKnownType attribute.
By default, "$type" is used for discriminator property name, if you need to change that use JsonDiscriminator attribute.

[JsonConverter(typeof(JsonKnownTypesConverter<BaseClass>))]
[JsonDiscriminator(Name = "myType")] //add custom discriminator name
[JsonKnownType(typeof(BaseClass1Heir))] //could be deleted if you didn't turn off UseClassNameAsDiscriminator
[JsonKnownType(typeof(BaseClass2Heir), "myDiscriminator")]
public class BaseClass { ... }
  
public class BaseClass1Heir : BaseClass  { ... }
 
public class BaseClass2Heir : BaseClass  { ... }

Json representation:

{ ... , "myType":"BaseClass" }

{ ... , "myType":"BaseClass1Heir" }

{ ... , "myType":"myDiscriminator" }

JsonKnownThisType

Add a discriminator for type which is used with it:

[JsonConverter(typeof(JsonKnownTypesConverter<BaseClass>))]
[JsonKnownThisType("do_you_know_that")]
public class BaseClass { ... }

[JsonKnownThisType("html_is_programming_language")]
public class BaseClass1Heir : BaseClass  { ... }
  
[JsonKnownThisType("just_joke=)")]
public class BaseClass2Heir : BaseClass  { ... }

Json representation:

{ ... , "$type":"do_you_know_that" }

{ ... , "$type":"html_is_programming_language" }

{ ... , "$type":"just_joke=)" }

Configuration

To change default discriminator settings use:

JsonKnownTypesSettingsManager.DefaultDiscriminatorSettings = new JsonDiscriminatorSettings
{
    DiscriminatorFieldName = "name",
    UseClassNameAsDiscriminator = false
};

DiscriminatorFieldName change default "$type" name to yours

If UseClassNameAsDiscriminator is false you should add JsonKnownType or JsonKnownThisType attribute for each relative class manually otherwise it will throw an exception.

If you want to add derived types from another assembly you can set custom type resolver Func<Type, Type[]>:

JsonKnownTypesSettingsManager.GetDerivedByBase = parent => parent.Assembly.GetTypes();

Use manually

public class BaseClass { ... }
public class BaseAbstractClass1Heir : BaseClass  { ... }
public class BaseAbstractClass2Heir : BaseClass  { ... }
var converter = new JsonKnownTypesConverter<BaseClass>()
  
var entityJson = JsonConvert.SerializeObject(entity, converter);
var obj = DeserializeObject<BaseClass>(entityJson, converter)

You have to pass a converter directly to method if you do not use JsonConverter attribute.

Fallback type deserialization

Normally you will receive an exception during deserialization of models marked with unknown or unspecified type discriminator. If you need an exception-free way you can use JsonKnownTypeFallback attribute. In that case entities marked with unknown or missing type discriminator will be deserialized to specified fallback type. See example.

Assume you have a bunch of events coming from webhook/frontend/etc.:

[
  { id: "abc", opType: "op_start" },
  { id: "bcd", opType: "on_save" },
  { id: "cde", opType: "op_update" },
  { id: "def", opType: "op_end" }
]

Then in your application you can do the following to handle only events you are only interested of:

[JsonConverter(typeof(JsonKnownTypesConverter<OperationBase>))]
[JsonDiscriminator(Name = "opType")]
[JsonKnownType(typeof(OperationStarted), "op_start")]
[JsonKnownType(typeof(OperationEnded), "op_end")]
[JsonKnownTypeFallback(typeof(UnsupportedOperation))]
public abstract class OperationBase
{
    public string Id { get; set; }
}

public class OperationStarted : OperationBase { }
public class OperationEnded : OperationBase { }
public class UnsupportedOperation : OperationBase { }

Breaking changes

Documented API can be changed, because it is zero version still. And I'm trying to find better solution and always add some fixes and this fixes also can change some behavior.

There are a lot of undocumented public API and you can use it but i can change it any time.

So when you install new version check all of these.

How to help us?

I need feedback, if you have suggestion or some issue create an issue and describe it, even if you think it's not critical.

Also you can buy me a coffee 🤗

License

Authored by: Dmitry Kaznacheev (dmitry-bym)

This project is under MIT license. You can obtain the license copy here.

This work using work of James Newton-King, author of Json.NET. https://www.newtonsoft.com/json

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].