Friday, October 9, 2020

JsonSrcGen 0.2.0 Alpha Released

JsonSrcGen 0.2.0 Alpha Released

JsonSrcGen 0.2.0 alpha has been published. This release contains the following changes:

Breaking Changes
  • Serialise to ReadOnlySpan<char> instead of string
  • JsonSrcGenConvert renamed to JsonConverter
New Features
  • Support for Json Values
  • Support for Custom Converters
  • Support for char

Serialise to ReadOnlySpan<char> instead of string

To Json conversions now produce ReadOnlySpan<char> instead of string, is produces a significant speedup as it allows us to avoid the memory allocation required to create the String. The ReadOnlySpan reuses the same memory for each ToJson conversion within a thread. Because of this the ReadOnlySpan must be consumed before calling ToJson again or the data it points at will change.


Support for Json Values

Simple Json Values can not be convertered to and from Json. To do this you must specify a JsonValue attribute at the solution level as follows:


[assembly: JsonValue(typeof(int))]

...

var converter = new JsonConverter

ReadOnlySpan<char> json = converter.ToJson(1456);

int value = converter.FromJson(0, "1456"); 

Support for Custom Converters

Custom Converters allow you to provide a custom conversion code for a type. To do so you must implement ICustomConverter<T> and add the CustomConverter attribute to 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
    }
}

Please checkout the JsonSrcGen project on github: https://github.com/trampster/JsonSrcGen

JsonSrcGen is available as a nuget package:

No comments: