https://stackoverflow.com/questions/68475544/select-part-of-json-with-system-text-json

CSharp · Console

/Program.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Collections.ObjectModel;
using System.Net;

using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;	

using System.Text.Json;

using NUnit.Framework; // Throws NUnit.Framework.AssertionException

//https://stackoverflow.com/questions/68475544/select-part-of-json-with-system-text-json

	public static partial class JsonExtensions
	{
		// Copied from this answer https://stackoverflow.com/a/59047063/3744182
		// By https://stackoverflow.com/users/3744182/dbc
		// To https://stackoverflow.com/questions/58138793/system-text-json-jsonelement-toobject-workaround
		public static T ToObject<T>(this JsonElement element, JsonSerializerOptions options = null)
		{
			var bufferWriter = new System.Buffers.ArrayBufferWriter<byte>();
			using (var writer = new Utf8JsonWriter(bufferWriter))
				element.WriteTo(writer);
			return JsonSerializer.Deserialize<T>(bufferWriter.WrittenSpan, options);
		}

		public static T ToObject<T>(this JsonDocument document, JsonSerializerOptions options = null)
		{
			if (document == null)
				throw new ArgumentNullException(nameof(document));
			return document.RootElement.ToObject<T>(options);
		}       
	}

	public class Retailer // NOT INCLUDED IN QUESTION
	{
	}

    public class CarteGraphique
    {
        public string displayName { get; set; }
        public string PrdStatus { get; set; }
        public List<Retailer> retailers { get; set; }
    }

    class TestClass
    {
        public static void Test()
		{
			var url = @"https://api.nvidia.partners/edge/product/search?page=1&limit=9&locale=fr-fr&category=GPU&gpu=RTX%203090,RTX%203080%20Ti,RTX%203080,RTX%203070%20Ti,RTX%203070,RTX%203060%20Ti,RTX%203060&gpu_filter=RTX%203090~12,RTX%203080%20Ti~7,RTX%203080~16,RTX%203070%20Ti~3,RTX%203070~18,RTX%203060%20Ti~8,RTX%203060~2,RTX%202080%20SUPER~1,RTX%202080~0,RTX%202070%20SUPER~0,RTX%202070~0,RTX%202060~6,GTX%201660%20Ti~0,GTX%201660%20SUPER~9,GTX%201660~8,GTX%201650%20Ti~0,GTX%201650%20SUPER~3,GTX%201650~17";
			using var client = new WebClient();
			
			var json = client.DownloadString(url);

			TestSystemTextJson(json);
			TestNewtonsoft(json);
		}
		
		static void TestSystemTextJson(string json)
		{
			Console.WriteLine("\nParsing with System.Text.Json...");
			
			using var jsonParse = JsonDocument.Parse(json); // Be sure to dispose the JsonDocument!

			var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
			
			var products = jsonParse.RootElement
				.GetProperty("searchedProducts") // Get the searchedProducts value
				.GetProperty("productDetails")   // Get the productDetails value
				.EnumerateArray()                // Enumerate its items
				.Where(n => n.GetProperty("isFounderEdition").GetBoolean()) // Filter on those for which isFounderEdition == true
				.Select(n => n.ToObject<CarteGraphique>(options)) // Deserialize to a CarteGraphique
				.ToList();
				
			// Add the searchedProducts.featuredProduct item to the list.
			var featuredProduct = jsonParse.RootElement
				.GetProperty("searchedProducts")
				.GetProperty("featuredProduct")
				.ToObject<CarteGraphique>(options);

			products.Add(featuredProduct);
			
            foreach (var item in products)
            {
                Console.WriteLine(item.displayName); // Fixed DisplayName
            }
		}
		
        public static void TestNewtonsoft(string json)
        {
			Console.WriteLine("\nParsing with Newtonsoft...");
			
            JObject jsonParse = JObject.Parse(json);

            IList<CarteGraphique> products = new List<CarteGraphique>();

            IList<JToken> productDetailsParse = jsonParse["searchedProducts"]["productDetails"]
                .Children()
                .Where(n => n["isFounderEdition"].Value<bool>() == true)
                .ToList();
            var featuredProductParse = jsonParse["searchedProducts"]["featuredProduct"];


            foreach (JToken item in productDetailsParse)
            {
                CarteGraphique result = item.ToObject<CarteGraphique>();
                products.Add(result);
            }
            var featuredProduct = featuredProductParse.ToObject<CarteGraphique>();

            products.Add(featuredProduct);



            foreach (var item in products)
            {
                Console.WriteLine(item.displayName); // Fixed DisplayName
            }
		}	
	}

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
			Console.WriteLine("{0} version: {1}", typeof(Newtonsoft.Json.JsonSerializer).Assembly.GetName().Name,  typeof(Newtonsoft.Json.JsonSerializer).Assembly.FullName);
			Console.WriteLine();

			try
			{
				TestClass.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Failed with unhandled exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
		
		public static string GetNetCoreVersion()
		{
			//https://techblog.dorogin.com/how-to-detect-net-core-version-in-runtime-ecd65ad695be
			//
			var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
			var assemblyPath = assembly.Location.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
			int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
			if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
				return assemblyPath[netCoreAppIndex + 1];
			return null;
		}
	}
;