字典<string,dynamic>的NEST映射获取空数组

时间:2018-06-28 15:01:44

标签: c# elasticsearch nest

当尝试从我的数据库反序列化包含Json的字段以在Elasticsearch中建立索引时,所有嵌套字段都将空数组作为值。

{
    "_index": "dev",
    "_type": "user",
    "_id": "072512c2-fc23-471a-9e07-65c3a041f06b",
    "_score": 1,
    "_source": {
      "providerInfos": """{"Global":{"Email":"email@hotmail.com","FirstName":"Name","LastName":"Last Name","PostalCode":"XXXXXX","Address":"99 Street","Town":"City","Gender":"M","PhoneNumber":null,"CreatedDate":"2018-04-14T14:34:42.4850547Z","LastLoginDate":"0001-01-01T00:00:00"}}""",
      "providers": {
        "Global": {
          "Email": [],
          "FirstName": [],
          "LastName": [],
          "PostalCode": [],
          "Address": [],
          "Town": [],
          "Gender": [],
          "PhoneNumber": [],
          "CreatedDate": [],
          "LastLoginDate": []
        },

我要反序列化的代码如下:

public class User : IdentityUser

  public string JsonInfo { get; protected set; }

    [NotMapped]
    public Dictionary<string, dynamic> Infos
    {
        get => JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(JsonInfo ?? "") ??
               new Dictionary<string, dynamic>();
    }
}

在我数据库的JsonInfo字段中,例如:

{"Global":{"Email":"email@hotmail.com","FirstName":"Name","LastName":"Last Name","PostalCode":"XXXXXX","Address":"99 Street","Town":"City","Gender":"M","PhoneNumber":null,"CreatedDate":"2018-04-14T14:34:42.4850547Z","LastLoginDate":"0001-01-01T00:00:00"}}

并为其全部编制索引:

var users = await uow.GetRepository<FedecpIdentityUser, string>().GetAsync();
var indexAllAsync = users
    .Select(u => _elasticSearch.Client.IndexAsync(u, p => p.Id(u.Id.ToString()))).ToList();

我注意到这是在将Nest从5.4更新到6.02之后发生的,是吗?我在变更日志中什么都没找到。

1 个答案:

答案 0 :(得分:0)

我怀疑这与6.x中Json.NET的内部化以及代码中dynamic的使用有关。

dynamic实际上将由Json.NET反序列化为JToken类型,NEST不知道如何序列化,因为出于所有意图和目的而内部化的Json.NET可以被视为不同的程序集对Newtonsoft.Json类型一无所知。

要解决此问题,您可以引用Nest.JsonNetSerializer nuget packagehook up the JsonNetSerializer as the serializer作为NEST来用于文档

var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var connectionSettings =
    new ConnectionSettings(pool, sourceSerializer: JsonNetSerializer.Default);
var client = new ElasticClient(connectionSettings);