PropertyGrid TypeConverter conflicits with NewtonSoft json

26 Views Asked by At

The following code:

using Newtonsoft.Json;
using System.ComponentModel;

// Serialize
Dictionary<string, MyClass> d = new Dictionary<string, MyClass>();
MyClass obj = new MyClass { Id = 1, Name = "John Doe" };
d["A"] = obj;

string json = JsonConvert.SerializeObject(d);
Console.WriteLine(json);

public class B
{
    public int x { get; set; }
}

[TypeConverter(typeof(ExpandableObjectConverter))]
public class MyClass
{
    public int Id { get; set; }
    public string Name { get; set; }
    public B b { get; set; } = new B();
}

Failed to serialize MyClass and only show "MyClass" not data, due to the TypeConverter. But I need it for PropertyGrid showing. Any simple way to ignore the TypeConverter when serialized?

1

There are 1 best solutions below

0
kilasuelika On

Thanks to @dbc, following code is desired:

using System.ComponentModel;
using System.Text.Json;
using System.Text.Json.Serialization;

// Serialize
Dictionary<string, MyClass> d = new Dictionary<string, MyClass>();
MyClass obj = new MyClass { Id = 1, Name = "John Doe" };
d["A"] = obj;

JsonSerializerOptions options = new()
{
    ReferenceHandler = ReferenceHandler.Preserve,
    WriteIndented = true
};

string json = JsonSerializer.Serialize(d, options);
Console.WriteLine(json);
public class B
{
    public int x { get; set; }
}

[TypeConverter(typeof(ExpandableObjectConverter))]
public class MyClass
{
    public int Id { get; set; }
    public string Name { get; set; }
    public B b { get; set; } = new B();
}