Json library that uses .NET 5 c# Source Generators
Note: Requires the .Net 5 Preview to run. Mono platforms do not have support for the .Net 5 Source Generators yet.
Classes Class serializers can be generated by defining a Json attribute on the class
[Json]
public class MyType
{
[JsonName("my_name")]
public string MyProperty {get;set}
[JsonIgnore]
public string IgnoredProperty {get;set;}
}
var converter = new JsonConverter();
ReadOnlySpan<char> json = convert.ToJson(new MyType(){MyProperty = "Some value"});
var myType = new MyType();
convert.FromJson("{\"MyProperty\:\"Some value\"}", myType);
Properties with the following types are supported:
Integer Types | Others |
---|---|
int | float |
int? | float? |
uint | double |
uint? | double? |
ushort | boolean |
ushort? | boolean? |
short | string |
short? | DateTime |
byte | DateTime? |
byte? | Guid |
long | Arrays |
long? | List |
Arrays
Arrays are generated by defining a JsonArray attribute at the assembly level.
[assembly: JsonArray(typeof(bool))]
List
Lists are generated by defining a JsonList attribute at the assembly level.
[assembly: JsonList(typeof(bool))]
Dictionary
Dictionaries are generated by defining a JsonList attribute at the assembly level. Only Dictionaries with string keys are supported currently.
[assembly: JsonDictionary(typeof(string), typeof(int))]
Values
Simple json values are generated by defining a JsonValue attribute at the assembly level.
[assembly: JsonValue(typeof(int))]
Custom Converters
You can customize the conversion for specific types by providing your own converter. You must implement ICustomConverter and put the CustomConverter attribute on your class.
[CustomConverter(typeof(int))]
public class CustomCaseStringConverter : ICustomConverter<int>
{
public void ToJson(IJsonBuilder builder, int value)
{
// Write your json to the builder here
}
public ReadOnlySpan<char> FromJson(ReadOnlySpan<char> json, ref int value)
{
// Read the Json from the json span here
}
}
Nuget Packages
JsonSrcGen is available as a nuget package: https://www.nuget.org/packages/JsonSrcGen/