c# - JsonDerivedType - rename type discriminator - Stack Overflow

admin2025-04-19  7

I have classes with polymorphism active e.g.

[JsonDerivedType(typeof(DerivedClass1), "derivedClass1")]
[JsonDerivedType(typeof(Foo), "foo")]
public abstract class BaseClass
{

}

public class DerivedClass1 : BaseClass
{

}

public class Foo : BaseClass
{

}

I want to rename the class Foo to Bar

[JsonDerivedType(typeof(DerivedClass1), "derivedClass1")]
//renamed Foo to Bar, also adjusted the type discriminator to bar
[JsonDerivedType(typeof(Bar), "bar")]
public abstract class BaseClass
{

}

public class DerivedClass1 : BaseClass
{

}

//renamed Foo to Bar
public class Bar : BaseClass
{

}

BUT I want to still support old json files with the old name.

So while deserializing it should deserialize EITHER Bar or Foo into the class Bar, on serializing the class it should use the current name Bar.

I only know of the "cheesy" way to read the file into memory, do a basic string replace fileContent = fileContent.Replace(oldName, newName); and than deserialize the string fileContent.

转载请注明原文地址:http://anycun.com/QandA/1745036238a90355.html