我怎样才能反序列化一些子树

How can I deserialize some subtree only

我有一个 JSON 文档,例如

{
   "outer":{
      "inner":{ ... }
   }
}

如何使用 System.Text.Json"inner"{ ... })的值反序列化为某种类型 MyType

您可以尝试使用 JsonDocument class。下面 link 中的一个部分解释了它如何使用示例代码。

https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/

您可以这样使用 JsonDocument


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());
}

但不确定性能方面(我认为您可以使用一些 tricks 来提高这个天真的解决方案的性能,但仍然)它会比创建相应的结构更好。

在 .NET 5 中,您可以将 JSON 反序列化为包装所需类型的匿名类型:

var myType = JsonSerializerExtensions.DeserializeAnonymousType(jsonString, 
                                                               new { outer = new { inner = default(MyType) } })
    ?.outer?.inner;

使用 :

中的扩展方法
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
}

这应该比反序列化为中间 JsonDocument 更高效。但请注意,这在 .NET Core 3.x 中不起作用,因为该版本不支持反序列化为具有参数化构造函数的类型。

演示 fiddle here.