I'm deserializing a JSON list to object[] and expectedly get an array of object. I'd like however to deserialize to more specific types. Is there a way to do that, possibly with supplying the exact type on serialization? Unfortunatly I'm not able to be more specific than object[] in my code...
using System.Text.Json;
namespace Tests.DeSerialize;
class Program
{
public static void Main(string[] args)
{
object[] objs = new object[]{
42,
"foobar",
false,
new Example {
Name = "example",
}
};
foreach (var obj in objs)
{
Console.WriteLine(obj.GetType().Name);
}
var serialized = JsonSerializer.Serialize(objs);
Console.WriteLine();
Console.WriteLine(serialized);
Console.WriteLine();
object[] deSerializedObjs = JsonSerializer.Deserialize<object[]>(serialized);
foreach (var obj in deSerializedObjs)
{
Console.WriteLine(obj.GetType().FullName);
}
}
}
public class Example
{
public string Name { get; set; }
public override string ToString() => $"{GetType().Name}(\"{Name}\")";
}
Output:
Int32
String
Boolean
Example
[42,"foobar",false,{"Name":"example"}]
System.Text.Json.JsonElement
System.Text.Json.JsonElement
System.Text.Json.JsonElement
System.Text.Json.JsonElement
Is there a way to somehow encode the exact type into the serialized text?