c# - 通过 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
属性包含我要反序列化的数据。其他一切都只是我不关心的元数据。
有没有办法做到这一点?如果是这样,怎么做?
解决方案
您可以使用 Json.Net 的LINQ-to-JSON API来获取您感兴趣的节点,然后将它们转换为结果列表:
var results = JToken.Parse(response.Body)
.SelectTokens("hits.hits[*]._source")
.Select(t => t.ToObject<Result>())
.ToList();
推荐阅读
- localization - 如何用 next18-next 翻译 yup 错误?
- python - Flask:重定向到同一页面并保持状态
- javascript - 使用离子搜索栏时组件状态未正确更新
- python - 浮点列表中的最大值索引 | Python
- rest - Microsoft graph api - Outlook - 仅返回最新邮件
- mongodb - mongo db的用户名和密码是什么
- docker - 找不到应该在我正在运行的 docker 容器中的文件
- node.js - (节点:5151)UnhandledPromiseRejectionWarning
- java - 修复数组的索引超出范围?
- mysql - Nodejs Mocha 测试失败 Jenkins