私は下の例のシリアル化をテストしようとしていますが、このエラーが発生しました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;
}
を、それは非常に小さなmistake.Iは次のように' ElasticClient'をインスタンス化する前にJsonSerializerSettingsを設定していました。 SetJsonSerializerSettingsModifier(p => p.Converters.Add(new AssetTypeConverter())); _ elasticClient = new ElasticClient(connectionSettings); ' – user2768439
あなたは回答として投稿できます –