首页 > 解决方案 > 通过 JSON.NET 反序列化 Elasticsearch 结果

问题描述

我有一个 .NET 应用程序,我想用它来查询 Elasticsearch。我正在成功查询我的 Elasticsearch 索引。结果与此类似:

{
  "took":31,
  "timed_out":false,
  "_shards": {
    "total":91,
    "successful":91,
    "skipped":0,
    "failed":0
  },
  "hits":{
    "total":1,
    "max_score":1.0,
    "hits":[
      {
        "_index":"my-index",
        "_type":"doc",
        "_id":"TrxrZGYQRaDom5XaZp23",
        "_score":1.0,
        "_source":{
          "my_id":"65a107ed-7325-342d-adab-21fec0a97858",
          "host":"something",
          "zip":"12345"
        }
      },
    ]
  }
}

现在,这些数据可通过I'm getting back from ElasticsearchBody上的属性获得。StringResponse我想将实际记录(我不想要或不需要 , 等属性)反序列took化为timed_out名为results. 为了做到这一点,我有:

var results = JsonConvert.DeserializeObject<List<Result>>(response.Body);

该类Result如下所示:

public class Result
{
  [JsonProperty(PropertyName = "my_id")]
  public string Id { get; set; }

  [JsonProperty(PropertyName = "host")]
  public string Host { get; set; }

  [JsonProperty(PropertyName = "zip")]
  public string PostalCode { get; set; }
}

当我运行它时,我收到以下错误:

无法将当前 JSON 对象反序列化为类型“System.Collections.Generic.List`1[Result]”,因为该类型需要 JSON 数组才能正确反序列化。

虽然错误是有道理的,但我不知道如何解析hits来提取_source数据。该_source属性包含我要反序列化的数据。其他一切都只是我不关心的元数据。

有没有办法做到这一点?如果是这样,怎么做?

标签: c#elasticsearchjson.net

解决方案


您可以使用 Json.Net 的LINQ-to-JSON API来获取您感兴趣的节点,然后将它们转换为结果列表:

var results = JToken.Parse(response.Body)
                    .SelectTokens("hits.hits[*]._source")
                    .Select(t => t.ToObject<Result>())
                    .ToList();

工作演示:https ://dotnetfiddle.net/OkEpPA


推荐阅读