https://stackoverflow.com/questions/53857097

CSharp · Console

/Program.cs

using System;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
					
public class Program
{
	public static void Main()
	{
		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""
                    }
                  },
                  {
                    ""_index"": ""my-index"",
                    ""_type"": ""doc"",
                    ""_id"": ""jhgDtrEYHrjgJafgRy456"",
                    ""_score"": 0.95,
                    ""_source"": {
                      ""my_id"": ""52f0be23-1d2f-4779-bde9-32fc9e50168e"",
                      ""host"": ""something else"",
                      ""zip"": ""06789""
                    }
                  }
                ]
              }
            }";

		var results = JToken.Parse(json)
			                .SelectTokens("hits.hits[*]._source") 
			                .Select(t => t.ToObject<Result>())
			                .ToList();
		
		foreach (var result in results)
		{
			Console.WriteLine("Id: " + result.Id);
			Console.WriteLine("Host: " + result.Host);
			Console.WriteLine("PostalCode: " + result.PostalCode);
			Console.WriteLine();
		}
	}
}

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; }
}
;