RSCG – JsonPolymorphicGenerator

RSCG – JsonPolymorphicGenerator
 
 

name JsonPolymorphicGenerator
nuget https://www.nuget.org/packages/GoLive.Generator.JsonPolymorphicGenerator/
link https://github.com/surgicalcoder/JsonPolymorphicGenerator
author surgicalcoder

Generating JsonDerivedType to be added to the base class

 

This is how you can use JsonPolymorphicGenerator .

The code that you start with is


<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="GoLive.Generator.JsonPolymorphicGenerator" Version="1.0.4">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>

	<PropertyGroup>
		<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
		<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
	</PropertyGroup>

</Project>


The code that you will use is


//https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/polymorphism?pivots=dotnet-7-0
using JsonPolymorphicGeneratorDemo;
using System.Text.Json;

Person[] persons = new Person[2];
persons[0] = new Student() { Name="Student Ignat"};

persons[1] = new Teacher() { Name = "Teacher Ignat" };
JsonSerializerOptions opt = new ()
{
    WriteIndented = true
};
var ser = JsonSerializer.Serialize(persons, opt);
Console.WriteLine(ser);
var p = JsonSerializer.Deserialize<Person[]>(ser);
if(p != null)
foreach (var item in p)
{
    Console.WriteLine(item.Data());
}


using System.Text.Json.Serialization;

namespace JsonPolymorphicGeneratorDemo;

[JsonPolymorphic]
public abstract partial class Person
{
    
    public string? Name { get; set; }
    public abstract string Data();
}

public class Teacher : Person
{
    public override string Data()
    {
        return "Class Teacher:" + Name;
    }
}
public class Student : Person
{
    public override string Data()
    {
        return "Class Student:" + Name;
    }
}


 

The code that is generated is

using System.Text.Json.Serialization;

namespace JsonPolymorphicGeneratorDemo
{
    [JsonDerivedType(typeof(JsonPolymorphicGeneratorDemo.Teacher), "Teacher")]
    [JsonDerivedType(typeof(JsonPolymorphicGeneratorDemo.Student), "Student")]
    public partial class Person
    {
    }
}



Code and pdf at

https://ignatandrei.github.io/RSCG_Examples/v2/docs/JsonPolymorphicGenerator