【发布时间】:2016-04-25 10:30:24
【问题描述】:
我正在尝试测试以下示例的序列化,但我最终收到此错误Newtonsoft.Json.JsonSerializationException : Could not create an instance of type Core.Model.Assets.Asset. Type is an interface or abstract class and cannot be instantiated. Path '_source.articleAssets[0].asset.refId'。在下面的例子中,Asset 是一个抽象类,并且有超过 5 个派生类(例如:BrightcoveVideo 是派生类之一)
ArticleAssets = new List<ArticleAsset>()
{
new ArticleAsset()
{
ArticleId = 1,
Asset = new BrightcoveVideo()
{
AssetType = AssetTypeEnum.BrightcoveTitle, Id = 11, Name = "something for a name", DisplayName = "some display", RefId = "refrefref"
},
AssetId = 11,
AssetType = AssetTypeEnum.BrightcoveTitle
}
}
我有一个自定义的 JsonConverter 类,如下所示:
public class AssetTypeConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Asset) || objectType == typeof(SearchResultAsset);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value != null && value.GetType() == typeof(SearchResultAsset))
{
throw new NotImplementedException("WriteJson unexpectedly called for SearchResultAsset in AssetTypeConverter");
}
throw new NotImplementedException("WriteJson unexpectedly called for Asset in AssetTypeConverter");
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
Asset concreteAsset = new SearchResultAsset();
serializer.Populate(reader, concreteAsset);
return concreteAsset;
}
}
在 ElasticSearchRegistry 类中,我通过以下方式添加此转换器:
var connectionSettings = new ConnectionSettings(connectionUri);
_elasticClient = new ElasticClient(connectionSettings);
connectionSettings.SetJsonSerializerSettingsModifier(p => p.Converters.Add(new AssetTypeConverter()));
我在以下Get 请求中收到 JsonSerialization 异常:
public IGetResponse<Article> GetArticleResponse(int id)
{
var response = _elasticClient.Get<Article>(i => i.Index(_indexName)
.Type(DocumentType)
.Id(id)
);
return response;
}
【问题讨论】:
-
我已经修复了,这是一个很小的错误。我在实例化
ElasticClient之前设置了 JsonSerializerSettings,如下所示:connectionSettings = new ConnectionSettings(connectionUri);connectionSettings.SetJsonSerializerSettingsModifier(p => p.Converters.Add(new AssetTypeConverter()));_elasticClient = new ElasticClient(connectionSettings); -
您可以将其发布为答案