I came across the same issue, so I wrote some extension methods which work fine for now. It would be nice if they provided this as built in to avoid the additional allocation to a string.
public static T ToObject<T>(this JsonElement element)
{
var json = element.GetRawText();
return JsonSerializer.Deserialize<T>(json);
}
public static T ToObject<T>(this JsonDocument document)
{
var json = document.RootElement.GetRawText();
return JsonSerializer.Deserialize<T>(json);
}
Then use as follows:
jDoc.RootElement.GetProperty("SomeProperty").ToObject<SomeClass>();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…