【发布时间】:2019-10-14 11:33:39
【问题描述】:
考虑下面的代码。 当我尝试通过调用“SaveToFile”方法对其进行序列化时,“名称”属性不会被序列化。
有什么想法吗?
public class Subs
{
public string Something { get; set; } = "smew";
}
public class Plep : List<Subs>
{
public string Name { get; set; } = "smew";
public void SaveToFile(string file)
{
using (StreamWriter wrt = new StreamWriter(file))
{
wrt.WriteLine(JsonConvert.SerializeObject(this, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
//TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple,
}));
}
}
}
【问题讨论】:
-
你希望它如何被序列化为 JSON?作为具有属性的数组或对象?这些是不兼容的,Newtonsoft 似乎回退到列表/数组。
-
你为什么还要从列表中派生?通常你不需要这个。而只是使用一个列表,例如通过公开
List<Subs>。
标签: c# json inheritance