System.Text:JsonSerializer.Deserialize 使用泛型

mal*_*lat 7 c# json

我试图理解文档:

我的目标只是使用 System.Text.Json.JsonSerializer (dotnet 5.0)加载DICOM/JSON 。从 C# 到 JSON 的步骤很简单:

private class DataElement<T>
{
  public string vr { get; set; }
  public List<T> Value { get; set; }
}
[...]
var dataset = new Dictionary<string, object>();
dataset.Add("00100021", new DataElement<string>() { vr = "LO", Value = new List<string>(1) { "Hospital A" }});
dataset.Add("00201206", new DataElement<int>() { vr = "IS", Value = new List<int>(1) { 4 } });
dataset.Add("00101030", new DataElement<double>() { vr = "DS", Value = new List<double>(1) { 72.5 } });
string jsonString = JsonSerializer.Serialize(dataset, serializeOptions);
File.WriteAllBytes("ds.json", Encoding.UTF8.GetBytes(jsonString));
Run Code Online (Sandbox Code Playgroud)

但反过来做似乎要复杂得多。

我应该如何为这 3 种可能的泛型(字符串、整数或双精度)实现自定义转换器?

Twi*_*tem 3

如果您想使用 System.Text 反序列化器,那么如果您提供要反序列化的内容,它就会让您接近。尝试这个:

JsonSerializer.Deserialize<Dictionary<string, DataElement<object>>>(jsonString);
Run Code Online (Sandbox Code Playgroud)

但是,如果您使用 NewtonSoft.Json 反序列化器,您仍然希望让它知道您的期望,但它会返回数值的实际类型;语法如下:

JsonConvert.DeserializeObject<Dictionary<string, DataElement<object>>>(jsonString);
Run Code Online (Sandbox Code Playgroud)