[Interface2NullObject]Debugger and Converter–part 5

 

It will be interesting to see the Null Object in the debugger with properties generated from interface -see  https://www.nuget.org/packages/rscg_Interface_to_null_object

 

This is not very difficult to generate once you have the interface with properties

The code for generating

01
02
03
04
05
06
07
08
09
10
11
12
13
14
public string DebuggerDisplay() 
{
    StringBuilder sb = new StringBuilder("[System.Diagnostics.DebuggerDisplay(");
    sb.Append("\"");
    foreach (var item in props)
    {
        sb.Append(item.Name);
        sb.Append(" = {");
        sb.Append(item.Name);
        sb.Append("} " );
    }
    sb.Append("\")]");
    return sb.ToString();
}

 

and the code generated is

 

1
2
[System.Diagnostics.DebuggerDisplay("FirstName = {FirstName} LastName = {LastName} Department = {Department} ")]
public partial class Employee_null : global::IntegrationConsole.IEmployee

 

More interesting is to have a converter in order to obtain from the JSON string the interface, not the object .

 

The code for generating is

 

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
public class @(Model.Name + "Converter") : System.Text.Json.Serialization.JsonConverter<@(Model.FullName)>
    {
    public override @Model.FullName Read(ref System.Text.Json.Utf8JsonReader reader, System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options)
    {
    // Deserialize the JSON to the concrete type @Model.Name
    return System.Text.Json.JsonSerializer.Deserialize<@nameClass>
        (ref reader, options);
        }
 
        public override void Write(System.Text.Json.Utf8JsonWriter writer, @Model.FullName value, System.Text.Json.JsonSerializerOptions options)
        {
        // Serialize the concrete type @Model.Name
        System.Text.Json.JsonSerializer.Serialize(writer, (@nameClass)value, options);
        }
        }

and the code generated is

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
//serialize and deserialize
var empString = JsonSerializer.Serialize(employee);
Console.WriteLine(empString);
//deserialize
 
var options = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true,
    DefaultBufferSize = 128
};
options.Converters.Add(new IDepartmentConverter());
options.Converters.Add(new IEmployeeConverter());
 
var emp2 = JsonSerializer.Deserialize<IEmployee>(empString,options);
ArgumentNullException.ThrowIfNull(emp2);
Console.WriteLine(emp2.FirstName);
Console.WriteLine(emp2.Department.Name);
Debug.Assert(emp2.FirstName == "Andrei");