当我将有关的Newtonsoft.json.dll从.NET 3.5更新到.NET 4.5时,基类不是序列化。在更新之前,基类正在序列化。
public class MyBaseClass
{
public string BaseProp1 { get; set; }
public string BaseProp2 { get; set; }
}
[DataContract]
public class MyDerivedClass : MyBaseClass
{
[DataMember]
public DateTime DerProp1 { get; set; }
public string DerProp2 { get; set; }
}
class Program
{
static void Main(string[] args)
{
MyDerivedClass derc = new MyDerivedClass();
derc.BaseProp1 = "BaseProp1";
derc.DerProp1 = DateTime.Now;
derc.BaseProp2 = "BaseProp2";
derc.DerProp2 = "DerProp2";
Newtonsoft.Json.Converters.IsoDateTimeConverter conv = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
conv.DateTimeFormat = "MM/dd/yyyy HH:mm:ss zzz";
string jsonSerializedObject = JsonConvert.SerializeObject(derc, conv);
}
}
程序不会序列化基类的成员。原因是我没有在基类中指定[DataContract]。我需要序列化所有成员。 问题:
最好的方法是什么?
答案 0 :(得分:5)
默认情况下会忽略基类属性。您可以通过创建自定义合约解析程序来更改此行为。
class MyContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var list = base.CreateProperties(type, memberSerialization);
foreach (var prop in list)
{
prop.Ignored = false; // Don't ignore any property
}
return list;
}
}
此解析器将有效确保不会忽略任何属性。如果你想要忽略某些属性,你可能想要应用一些逻辑。
使用解析器;创建一个JsonSerializerSettings
实例并将其提供给JsonConvert.SerializeObject
方法。
您的最后一行将替换为:
JsonSerializerSettings settings = new JsonSerializerSettings
{
ContractResolver = new MyContractResolver(),
Converters = { conv },
};
string jsonSerializedObject = JsonConvert.SerializeObject(derc, settings);
然后将基类属性序列化:
{
"DerProp1":"02-17-2015 13:39:29 +01:00",
"DerProp2":"DerProp2",
"BaseProp1":"BaseProp1",
"BaseProp2":"BaseProp2"
}
答案 1 :(得分:1)
使用JsonProperty
public class MyBaseClass
{
[JsonProperty("BaseProp1")]
public string BaseProp1 { get; set; }
[JsonProperty("BaseProp2")]
public string BaseProp2 { get; set; }
}
[DataContract]
public class MyDerivedClass : MyBaseClass
{
[JsonProperty("DerProp1")]
[DataMember]
public DateTime DerProp1 { get; set; }
[JsonProperty("DerProp2")]
public string DerProp2 { get; set; }
}