CSharp · Console
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/75251361/deserialize-different-items-into-a-list-of-objects-using-newtonsoft-json
public class File
{
public string FileName {get; set;} // The Lion King (2019) BluRay 1080p x264 (nItRo)-XpoZ.mkv
public long FileSize {get; set;} // 1819821931
}
public record Item ([property: JsonProperty("rd")] List<Dictionary<string, File>> Rd);
class TestClass
{
public static void Test()
{
var json = GetJson();
var root = JsonConvert.DeserializeObject<Dictionary<string, Item>>(json);
var newJson = JsonConvert.SerializeObject(root, Formatting.Indented);
Console.WriteLine("Re-serialized {0}", root);
Console.WriteLine(newJson);
}
static string GetJson() =>
"""
{
"a374e91a9f513c79a8961de7c494cf799bbdb35b": {
"rd": [
{
"1": {
"filename": "The Lion King (2019) BluRay 1080p x264 (nItRo)-XpoZ.mkv",
"filesize": 1819821931
}
}
]
},
"e999ddbb3e18613476546684e34a4a6b0cfec878": {
"rd": [
{
"1": {
"filename": "The.Lion.King.2019.1080p.BluRay.10bit.x265-HazMatt.mkv",
"filesize": 4256678521
}
}
]
},
"8bb877768a0780c9694767a655720927e6cda57e": {
"rd": []
}
}
""";
}
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;
}
}
}