I have a JSON document like
{
"outer":{
"inner":{ ... }
}
}
How can I deserialize the value of "inner"
(the { ... }
) into some type MyType
using System.Text.Json
?
I have a JSON document like
{
"outer":{
"inner":{ ... }
}
}
How can I deserialize the value of "inner"
(the { ... }
) into some type MyType
using System.Text.Json
?
In .NET 5, you can deserialize the JSON to an anonymous type that wraps the required type:
var myType = JsonSerializerExtensions.DeserializeAnonymousType(jsonString,
new { outer = new { inner = default(MyType) } })
?.outer?.inner;
Using the extension methods from Deserialize anonymous type with System.Text.Json:
public static partial class JsonSerializerExtensions
{
public static T DeserializeAnonymousType<T>(string json, T anonymousTypeObject, JsonSerializerOptions options = default)
=> JsonSerializer.Deserialize<T>(json, options);
public static ValueTask<TValue> DeserializeAnonymousTypeAsync<TValue>(Stream stream, TValue anonymousTypeObject, JsonSerializerOptions options = default, CancellationToken cancellationToken = default)
=> JsonSerializer.DeserializeAsync<TValue>(stream, options, cancellationToken); // Method to deserialize from a stream added for completeness
}
This should be more performant than deserializing to an intermediate JsonDocument
. But note this will not work in .NET Core 3.x as that version does not support deserializing to types with parameterized constructors.
Demo fiddle here.
You can try using the JsonDocument class. A section in the link below explains how it works with sample code.
https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/
You can use JsonDocument
like this:
public class MyType
{
public int id { get; set; }
}
var json = @"{
""outer"" : {
""inner"" : {""id"":1}
}}";
using (JsonDocument doc = JsonDocument.Parse(json))
{
var prop = doc.RootElement.GetProperty("outer").GetProperty("inner");
var myType = JsonSerializer.Deserialize<MyType>(prop.GetRawText());
}
But not sure that performance-wise (I think you can improve the performance of this naive solution using some tricks, but still) it would be better than creating corresponding structure.