Wil*_*ill 84 c# serialization json json.net
json.net(newtonsoft)
我正在查看文档,但我找不到任何关于这个或最好的方法来做到这一点.
public class Base
{
public string Name;
}
public class Derived : Base
{
public string Something;
}
JsonConvert.Deserialize<List<Base>>(text);
Run Code Online (Sandbox Code Playgroud)
现在我在序列化列表中有Derived对象.如何反序列化列表并返回派生类型?
Mad*_*nyo 88
您必须启用类型名称处理并将其作为设置参数传递给(反)序列化程序.
Base object1 = new Base() { Name = "Object1" };
Derived object2 = new Derived() { Something = "Some other thing" };
List<Base> inheritanceList = new List<Base>() { object1, object2 };
JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
string Serialized = JsonConvert.SerializeObject(inheritanceList, settings);
List<Base> deserializedList = JsonConvert.DeserializeObject<List<Base>>(Serialized, settings);
Run Code Online (Sandbox Code Playgroud)
这将导致派生类的正确反序列化.它的一个缺点是它将命名您正在使用的所有对象,因此它将命名您放置对象的列表.
kam*_*cus 39
如果您将类型存储在您的text(在本方案中应该如此),则可以使用JsonSerializerSettings.
请参阅:如何使用Newtonsoft JSON.NET将JSON反序列化为IEnumerable <BaseType>
但要小心.使用除此之外的任何东西都TypeNameHandling = TypeNameHandling.None可能导致自己陷入安全漏洞.
rzi*_*ppo 14
由于这个问题非常普遍,因此如果您想控制类型属性名称及其值,添加一些操作可能会很有用。
很长的路要走,那就是编写custom JsonConverter来通过手动检查和设置type属性来处理(反序列化)。
一种更简单的方法是使用JsonSubTypes,它通过属性处理所有样板:
[JsonConverter(typeof(JsonSubtypes), "Sound")]
[JsonSubtypes.KnownSubType(typeof(Dog), "Bark")]
[JsonSubtypes.KnownSubType(typeof(Cat), "Meow")]
public class Animal
{
public virtual string Sound { get; }
public string Color { get; set; }
}
public class Dog : Animal
{
public override string Sound { get; } = "Bark";
public string Breed { get; set; }
}
public class Cat : Animal
{
public override string Sound { get; } = "Meow";
public bool Declawed { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
小智 8
使用这个JsonKnownTypes,它的使用方式非常相似,只是在 json 中添加了鉴别器:
[JsonConverter(typeof(JsonKnownTypeConverter<BaseClass>))]
[JsonKnownType(typeof(Base), "base")]
[JsonKnownType(typeof(Derived), "derived")]
public class Base
{
public string Name;
}
public class Derived : Base
{
public string Something;
}
Run Code Online (Sandbox Code Playgroud)
现在,当你序列化JSON对象将增加"$type"与"base"和"derived"价值,这将是使用了反序列化
序列化列表示例:
[
{"Name":"some name", "$type":"base"},
{"Name":"some name", "Something":"something", "$type":"derived"}
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
86726 次 |
| 最近记录: |