通过json.net反序列化elasticsearch结果

ojsjcaue  于 2021-06-14  发布在  ElasticSearch
关注(0)|答案(5)|浏览(416)

我有一个.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"
        }
      },
    ]
  }
}

现在,这些数据可以通过 Body 上的属性 StringResponse 我从elasticsearch回来了。我想反序列化实际记录(我不想或不需要 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 属性包含要反序列化的数据。其他的都是我不在乎的元数据。
有办法吗?如果是,怎么做?

nle07wnf

nle07wnf1#

尝试使用vs特殊粘贴功能生成的以下结构:

public class Rootobject
{
    public int took { get; set; }
    public bool timed_out { get; set; }
    public _Shards _shards { get; set; }
    public Hits hits { get; set; }
}

public class _Shards
{
    public int total { get; set; }
    public int successful { get; set; }
    public int skipped { get; set; }
    public int failed { get; set; }
}

public class Hits
{
    public int total { get; set; }
    public float max_score { get; set; }
    public Hit[] hits { get; set; }
}

public class Hit
{
    public string _index { get; set; }
    public string _type { get; set; }
    public string _id { get; set; }
    public float _score { get; set; }
    public _Source _source { get; set; }
}

public class _Source
{
    public string my_id { get; set; }
    public string host { get; set; }
    public string zip { get; set; }
}
mfpqipee

mfpqipee2#

好吧,你是
DeserializeObject T 与json不匹配。您的json以 { 所以你的t必须是一个类(不是 IEnumerable 类型)。
让我们从外面开始,一路走进去:

{
  "took":31,
  "timed_out":false,
  "_shards": <object>
  "hits": <object>
}

所以:

public class SearchResult
{
  [JsonProperty("took")]
  public int Took { get; set; }
  [JsonProperty("timed_out")]
  public bool TimedOut { get; set; }
  [JsonProperty("_shards")]
  public Shards Shards { get; set; }
  [JsonProperty("hits")]
  public Hits Hits { get; set; }
}

下一个是 _shards ```
"_shards": {
"total":91,
"successful":91,
"skipped":0,
"failed":0
},

所以

public class Shards
{
[JsonProperty("total")]
public int Total { get; set; }
// etc...
}

那么 `hits` ```
{
  "total":1,
  "max_score":1.0,
  "hits": <IEnumerable because []>
}

所以

public class Hits
{
  [JsonProperty("total")]
  public int Total { get; set; }
  [JsonProperty("max_score")]
  public int MaxScore { get; set; }
  [JsonProperty("hits")]
  public List<Hit> Hits { get; set; }
}

那么 Hits 列表:

{
    "_index":"my-index",
    "_type":"doc",
    "_id":"TrxrZGYQRaDom5XaZp23",
    "_score":1.0,
    "_source":  <object>
},

所以

public class Hit
{
  [JsonProperty("_index")]
  public string Index { get; set; }
  // etc
}

一旦你创建了所有你需要的,然后你反序列化:

JsonConvert.DeserializeObject<SearchResult>(json);
cgfeq70w

cgfeq70w3#

您需要首先反序列化为泛型 JToken 或者 JObject ,如下所示:

var token = JsonConvert.DeserializeObject<JToken>(jsonString);

然后您可以导航到保存您感兴趣的数据的\u source属性:

var hitsArray = token["hits"]["hits"] as JArray;
var result = hitsArray[0]["_source"].ToObject<Result>();
1sbrub3j

1sbrub3j4#

我曾经http://json2csharp.com/ 为了将json转换成c类,在我的测试中,我从上的转换中得到了一个json字符串http://easyonlineconverter.com/converters/dot-net-string-escape.html
然后我用这个类创建了一个控制台应用程序:

using System.Collections.Generic;
using Newtonsoft.Json;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string json = "{  \"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\"        }      },    ]  }}";
            RootObject t = JsonConvert.DeserializeObject<RootObject>(json);
        }

        public class Shards
        {
            public int total { get; set; }
            public int successful { get; set; }
            public int skipped { get; set; }
            public int failed { get; set; }
        }

        public class Source
        {
            public string my_id { get; set; }
            public string host { get; set; }
            public string zip { get; set; }
        }

        public class Hit
        {
            public string _index { get; set; }
            public string _type { get; set; }
            public string _id { get; set; }
            public double _score { get; set; }
            public Source _source { get; set; }
        }

        public class Hits
        {
            public int total { get; set; }
            public double max_score { get; set; }
            public List<Hit> hits { get; set; }
        }

        public class RootObject
        {
            public int took { get; set; }
            public bool timed_out { get; set; }
            public Shards _shards { get; set; }
            public Hits hits { get; set; }
        }
    }
}

希望这有帮助

s5a0g9ez

s5a0g9ez5#

您可以使用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

相关问题