Question42022643 parsing-multiple-objects-using-jobject-in-newtonsoft-json-linq

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

    // https://stackoverflow.com/questions/42022643/parsing-multiple-objects-using-jobject-in-newtonsoft-json-linq


    public static class JsonExtensions
    {
        public static IEnumerable<T> DeserializeObjects<T>(Stream stream, JsonSerializerSettings settings = null)
        {
            var reader = new StreamReader(stream); // Caller should dispose
            return DeserializeObjects<T>(reader, settings);
        }

        public static IEnumerable<T> DeserializeObjects<T>(TextReader textReader, JsonSerializerSettings settings = null)
        {
            var ser = JsonSerializer.CreateDefault(settings);
            var reader = new JsonTextReader(textReader); // Caller should dispose

            reader.SupportMultipleContent = true;

            while (reader.Read())
            {
                if (reader.TokenType == JsonToken.None || reader.TokenType == JsonToken.Undefined || reader.TokenType == JsonToken.Comment)
                    continue;
                yield return ser.Deserialize<T>(reader);
            }
        }
    }

    public class Alternative
    {
        public string transcript { get; set; }
        public double confidence { get; set; }
    }

    public class Result
    {
        public List<Alternative> alternative { get; set; }
        public bool final { get; set; }
    }

    public class RootObject
    {
        public List<Result> result { get; set; }
        public int result_index { get; set; }
    }

    class TestClass
    {
        internal static void Test()
        {
            var json = @"{""result"":[]}
{""result"":[
          {""alternative"":[
                         {""transcript"":""hello Google how are you     feeling"",""confidence"":0.96274596},
                         {""transcript"":""hello Google how are you today"",""confidence"":0.97388196},
                         {""transcript"":""hello Google how are you picking"",""confidence"":0.97388196},
                         {""transcript"":""hello Google how are you kidding"",""confidence"":0.97388196}
                         ]
         ,""final"":true}]
,""result_index"":0
}";
            Console.WriteLine("Stream contents: ");
            Console.WriteLine(json);

            var HWR_Response = new HWR_Response(json);

			TestDeserialization(HWR_Response);
			
			TestLinqToJson(HWR_Response);
        }
		
		static void TestDeserialization(HWR_Response HWR_Response)
		{
            List<RootObject> results;
            using (var stream = HWR_Response.GetResonseStream())
            {
                results = JsonExtensions.DeserializeObjects<RootObject>(stream).ToList();
            }

			var transcripts = results
				.SelectMany(r => r.result)
				.SelectMany(r => r.alternative)
				.Select(a => a.transcript)
				.ToList();
			
			Console.WriteLine("Deserialized list of transcripts: ");
			Console.WriteLine(JsonConvert.SerializeObject(transcripts, Formatting.Indented));			
		}

		static void TestLinqToJson(HWR_Response HWR_Response)
		{
            List<JObject> objs;
            using (var stream = HWR_Response.GetResonseStream())
            {
                objs = JsonExtensions.DeserializeObjects<JObject>(stream).ToList();
            }
			
			var transcripts = objs
				// The following uses the JSONPath recursive descent operator ".." to pick out all properties named "transcript".
				.SelectMany(o => o.SelectTokens("..transcript")) 
				.Select(t => t.ToString())
				.ToList();
			
			Console.WriteLine("LINQ-to-JSON parsed list of transcripts: ");
			Console.WriteLine(JsonConvert.SerializeObject(transcripts, Formatting.Indented));
		}
		
		// Mockup class HWR_Response
        class HWR_Response
        {
            readonly string json;

            public HWR_Response(string json)
            {
                this.json = json;
            }

            public Stream GetResonseStream()
            {
                var ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
                ms.Position = 0;
                return ms;
            }
        }
    }


	public class Program
	{
		public static void Main()
		{
            Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);
            Console.WriteLine("");

			TestClass.Test();
		}
	}
;