Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Text: JsonSerializer.Deserialize with generics

Tags:

json

c#

I am trying to make sense of the documentation:

  • https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to?pivots=dotnet-5-0

My goal is simply to load DICOM/JSON using System.Text.Json.JsonSerializer (dotnet 5.0). The steps are easy from C# to 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));

But doing it the other way around seems much more complex.

How should I implement the custom converters for those 3 possible generics (string, int or double) ?

like image 527
malat Avatar asked Aug 14 '26 09:08

malat


2 Answers

If you want to use the System.Text deserializer, it will get you close if you supply what you are deserializing. Try this:

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

However if you use the NewtonSoft.Json deserializer, you will still want to let it know what you are expecting, but it will give you back the actual types for the numeric values; and the syntax looks like this:

JsonConvert.DeserializeObject<Dictionary<string, DataElement<object>>>(jsonString);
like image 154
Larry Dukek Avatar answered Aug 16 '26 00:08

Larry Dukek


It is more complex, but doable. Try decoding them in order of int -> double -> string since a double cannot be an int and anything that is not an int or double should be a string.

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();
like image 38
Jon Avatar answered Aug 16 '26 02:08

Jon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!