我正在使用 Json.NET 4.5 版本,我对 Json.Net 非常陌生。
问题:我需要知道 Json.NET 如何支持类的版本控制。
示例:如下例所示,我在第二个版本中有 EmployeeDetail 类,Name 属性分为 FirstName 和 LastName;和单个地址成为地址。
我尝试使用自定义 JsonConverter 在反序列化对象时提供向后兼容性,但在使用多个转换器时遇到了问题,因为我已经在使用常见的自定义创建 JsonConverter,它将 Interface 映射到 ConcreteType,如下例所示。
// Employee Detail Version 1.0
[JsonObject()]
public class EmployeeDetail
{
public EmployeeDetail()
{
}
public EmployeeDetail( string name )
{
Name = name;
}
[JsonProperty]
public string Name { get; set; }
[JsonConverterAttribute( typeof( CustomObjectCreationConverter<iAddress, Address> ) )]
public iAddress Address { get; set; }
}
// Employee Detail Version 2.0
[JsonObject()]
public class EmployeeDetail
{
public EmployeeDetail()
{
}
public EmployeeDetail( string firstName, string lastName )
{
FirstName = firstName;
LastName = lastName;
}
[JsonProperty]
public string FirstName { get; set; }
[JsonProperty]
public string LastName { get; set; }
[JsonConverterAttribute( typeof( CustomArrayCreationConverter<iAddress, Address> ) )]
public IEnumerable<iAddress> Addresses { get; set; }
}
最佳答案
向属性添加属性 [JsonConverterAttribute] 在这里并不是一个好的选择。相反,请尝试使用 TypeNameHandling = TypeNameHandling.Objects
和 TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
设置 JsonSerializerSettings
。
所以在使用设置序列化后,Json字符串将包含类似这样的标签 "地址":{"$type":"...
您可以使用 jObject.Property( "Address").Value 获取它
Var AddressValue = jObject.Property( "Address" ).Value
JsonTextReader textReader = new JsonTextReader( new StringReader( AddressValue.ToString() ) );
iAddress myAddress = serializer.Deserialize<iAddress>( textReader );
现在,如果地址对象尚未更改,那么它应该为您序列化它,否则您还需要另一个转换器。
您需要将这两个转换器传递给DeserializeObject
。
我还没有实际测试过这段代码,所以如果不清楚请告诉我
关于json.net - 我需要 Json.NET 中的类版本控制支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13302895/