NewtonSoft.Json 序列化和反序列化具有 IEnumerable<ISomeInterface> 类型属性的类 [英] NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface>
问题描述
我正在尝试移动一些代码来使用 ASP.NET MVC Web API 生成的 Json 数据而不是 SOAP Xml.
I am trying to move some code to consume ASP.NET MVC Web API generated Json data instead of SOAP Xml.
我遇到了序列化和反序列化类型属性的问题:
I have run into a problem with serializing and deserializing properties of type:
IEnumerable<ISomeInterface>.
这是一个简单的例子:
public interface ISample{
int SampleId { get; set; }
}
public class Sample : ISample{
public int SampleId { get; set; }
}
public class SampleGroup{
public int GroupId { get; set; }
public IEnumerable<ISample> Samples { get; set; }
}
}
我可以轻松地序列化 SampleGroup 的实例:
I can serialize instances of SampleGroup easily with:
var sz = JsonConvert.SerializeObject( sampleGroupInstance );
但是相应的反序列化失败了:
However the corresponding deserialize fails:
JsonConvert.DeserializeObject<SampleGroup>( sz );
带有此异常消息:
无法创建 JsonSerializationExample.ISample 类型的实例.类型是接口或抽象类,无法实例化."
"Could not create an instance of type JsonSerializationExample.ISample. Type is an interface or abstract class and cannot be instantated."
如果我派生一个 JsonConverter,我可以按如下方式装饰我的财产:
If I derive a JsonConverter I can decorate my property as follows:
[JsonConverter( typeof (SamplesJsonConverter) )]
public IEnumerable<ISample> Samples { get; set; }
这是 JsonConverter:
Here is the JsonConverter:
public class SamplesJsonConverter : JsonConverter{
public override bool CanConvert( Type objectType ){
return ( objectType == typeof (IEnumerable<ISample>) );
}
public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer ){
var jA = JArray.Load( reader );
return jA.Select( jl => serializer.Deserialize<Sample>( new JTokenReader( jl ) ) ).Cast<ISample>( ).ToList( );
}
public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer ){
... What works here?
}
}
此转换器解决了反序列化问题,但我无法弄清楚如何编写 WriteJson 方法以使序列化再次工作.
This converter solves the deserialization problem but I cannot figure how to code the WriteJson method to get serialization working again.
有人可以帮忙吗?
这是首先解决问题的正确"方法吗?
Is this a "correct" way to solve the problem in the first place?
推荐答案
你不需要使用 JsonConverterAttribute
,只要保持你的模型干净并使用 CustomCreationConverter
代替,代码更简单:
You don't need to use JsonConverterAttribute
, just keep your model clean and use CustomCreationConverter
instead, the code is simpler:
public class SampleConverter : CustomCreationConverter<ISample>
{
public override ISample Create(Type objectType)
{
return new Sample();
}
}
那么:
var sz = JsonConvert.SerializeObject( sampleGroupInstance );
JsonConvert.DeserializeObject<SampleGroup>( sz, new SampleConverter());
文档:使用 CustomCreationConverter 反序列化
这篇关于NewtonSoft.Json 序列化和反序列化具有 IEnumerable<ISomeInterface> 类型属性的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!