我正在尝试为以下示例测试序列化,但我最终收到此错误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;
}
答案 0 :(得分:0)
我修好了,这是一个非常小的错误。我在实例化JsonSerializerSettings
之前设置了ElasticClient
:
connectionSettings = new ConnectionSettings(connectionUri);
connectionSettings.SetJsonSerializerSettingsModifier(
p => p.Converters.Add(new AssetTypeConverter())
);
_elasticClient = new ElasticClient(connectionSettings);