簡體   English   中英

System.Text:JsonSerializer.Deserialize 與泛型

[英]System.Text: JsonSerializer.Deserialize with generics

我試圖理解文檔:

我的目標只是使用 System.Text.Json.JsonSerializer 加載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));

但反過來做似乎要復雜得多。

我應該如何為這 3 種可能的泛型(字符串、整數或雙精度)實現自定義轉換器?

它更復雜,但可行。 嘗試按照 int -> double -> string 的順序解碼它們,因為 double 不能是 int,任何不是 int 或 double 的東西都應該是字符串。

var intval = 0;
var dblval = 0.0;

if (int.TryParse(value, out intval)
   return intval;

if (double.TryParse(value, out dblval)
   return dblval;

return value.ToString();

如果你想使用 System.Text 反序列化器,如果你提供你正在反序列化的內容,它會讓你關閉。 試試這個:

JsonSerializer.Deserialize<Dictionary<string, DataElement<object>>>(jsonString);

但是,如果您使用 NewtonSoft.Json 反序列化器,您仍然希望讓它知道您的期望,但它會給您返回數值的實際類型; 語法如下所示:

JsonConvert.DeserializeObject<Dictionary<string, DataElement<object>>>(jsonString);

我的目標只是使用 System.Text.Json.JsonSerializer 加載 DICOM/JSON。

如果是這種情況,那么我建議您使用 NewtonSoft 的 Json 轉換器。 它更容易使用和理解(甚至是自定義轉換器)。

例子:

初始化

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 } });

節省

// Create a string for it
var json = JsonConvert.Serialize(MyDictionary);

加載

// Similar to your original object
var dict = JsonConvert.DeserializeObject<Dictionary<string, DataElement<object>>>(json);

測試

foreach (var element in dict)
{
    Console.WriteLine(JsonConvert.SerializeObject(element));
}

在此處輸入圖片說明


有關自定義轉換器的其他信息,請參閱下面的鏈接。 但是考慮到您的目標,我認為不需要自定義轉換器。 特別是如果你只想要一個Dictionary<string, object>出來。

https://www.newtonsoft.com/json/help/html/CustomJsonConverterGeneric.htm

為什么選擇 NewtonSoft

我遇到了內置 JsonSerializer 包將objects轉換為空值的問題,尤其是在聯網時。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM