我想爲下面的示例測試序列化,但我最終得到此錯誤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
是派生類中的一個)Newtonsoft.Json.JsonSerializationException:無法創建類型(抽象類)的實例
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()));
我得到的JsonSerialization除離子在Get
請求:
public IGetResponse<Article> GetArticleResponse(int id)
{
var response = _elasticClient.Get<Article>(i => i.Index(_indexName)
.Type(DocumentType)
.Id(id)
);
return response;
}
我得到它固定的,這是非常小犯錯誤實例'ElasticClient'像在此之前已經設置JsonSerializerSettings:'connectionSettings =新ConnectionSettings(connectionUri); connectionSettings。 SetJsonSerializerSettingsModifier(p => p.Converters.Add(new AssetTypeConverter())); _ elasticClient = new ElasticClient(connectionSettings);' – user2768439
您可以將它作爲答案發布 –