I'm porting a core 2.2 SDK to 3.0. Newtonsoft has been replaced by a native Json engine. My SDK takes a JObject and converts it to a concrete type using ToObject<T>()
Whats the equivalent of this with a JsonElement?
I want to deserialize a Message
class whose Event
property can only be determined at runtime :
private class Message
{
public string Type { get; set; }
public JsonElement Event { get; set; }
public string[] GenericArguments { get; set; }
public int? Id { get; set; }
}
In System.Text.Json I have to use this code to serialize the Event
to JSON and then deserialize it again to the final type :
private dynamic ParseTypeData(Message message)
{
Type type = typeFinder.GetEventType(message.Type);
if (message.GenericArguments.Length > 0)
{
var genericArguments = message.GenericArguments
.Select(typeFinder.GetType)
.ToArray();
type = type.MakeGenericType(genericArguments);
}
var json = message.Event.GetRawText();
return JsonSerializer.Deserialize(json, type, Options);
}
In JSON.NET the class was :
private class Message
{
public string Type { get; set; }
public JObject Event { get; set; }
public string[] GenericArguments { get; set; }
public int? Id { get; set; }
}
And deserializing Event
only needed :
return message.Event.ToObject(type);