Introducing JsonSrcGen
Over the last month I've been working on a new Json Library for .net that takes advantage of the new c# Source Generator feature that is being previewed in .NET 5. I've called this JsonSrcGen which is short for Json Source Generator.Why yet another Json library?
Source Generators allow us to generate optimal Json serialization code at compile time. Up until now Json Libraries have made heavy use of Reflection and Reflection.Emit to produce serialization code at runtime. But this approach has some draw backs.- Startup times are slow because of the reflection and time to emit the serialization code.
- AOT (Ahead of Time) platforms like Xamarin.iOS, Blazor and CoreRT struggle with Reflection and cannot do Reflection.Emit. Even if they can do reflection they can get significant size savings if they exclude it
- They require slow runtime lookups to match Types to generated Serializers
How do I use it?
Source Generators currently require .NET 5 and LangVersion set to 'preview'
<TargetFramework>net5.0</TargetFramework> <LangVersion>preview</LangVersion>
Add a nuget reference to our nuget package
Annotate your c# class with JsonSrcGen Attributes:
[Json] public class MyType { public int Age {get;set} [JsonName("my_property")] public string MyProperty {get;set} [JsonIgnore] public string IgnoredProperty {get;set;} }
Then use JsonSrcGenConvert instance to convert to and from Json strings.
var converter = new JsonSrcGenConvert(); //convert from Json MyType myType = new MyType(); converter.FromJson(myType, jsonString); //convert to json jsonString = converter.ToJson(new MyType());
Notice that when converting from Json you supply an already instantiated instance of the type, this allows you to reuse type instances and thus reduce memory allocations. Which adds up to a significant performance boost while deserializing.
No comments:
Post a Comment