https://stackoverflow.com/questions/78392886/c-sharp-json-deserialize-dynamic-type

CSharp · Console

/Program.cs

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

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

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

//https://stackoverflow.com/questions/78392886/c-sharp-json-deserialize-dynamic-type

public class MyApiResponseClass 
{
    //... other properties
    [JsonProperty("custom_attributes")]
    public List<CustomAttribute> CustomAttributes { get; set; } = new();
}

public class CustomAttribute
{
    [JsonProperty("attribute_code")]
    public string AttributeCode { get; set; } = string.Empty;

    [JsonProperty("value")]
    public object Value { get; set; } // = string.Empty;
}

    class TestClass
    {
        public static void Test()
        {
			var responseContent = GetJson();
			
			var response = JsonConvert.DeserializeObject<MyApiResponseClass>(responseContent);

			var newJson = JsonConvert.SerializeObject(response, Formatting.Indented);
			
			Console.WriteLine("Re-serialized {0}:", response);
			
			Console.WriteLine(newJson);
		}	
		
		static string GetJson() =>
"""
{
    "custom_attributes": [
        {
            "attribute_code": "required_options",
            "value": "simple"
        },
        {
            "attribute_code": "category_ids",
            "value": [
                "2"
            ]
        },
        {
            "attribute_code": "has_options",
            "value": "0"
        },
        {
            "attribute_code": "an_object",
            "value": {"0":"1"}
        }
    ]
}
""";
	}

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Environment version: {0} ({1}), {2}", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion);
			Console.WriteLine("{0} version: {1}", typeof(JsonSerializer).Namespace, typeof(JsonSerializer).Assembly.FullName);
			Console.WriteLine();

			try
			{
				TestClass.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Failed with unhandled exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
	}
;