c# - 使用System.Text.Json反序列化匿名类型

标签 c# json .net-core system.text.json .net-core-3.1

我正在更新.NET Core 3.x的一些应用程序,作为其中的一部分,我试图从Json.NET移到新的System.Text.Json类。使用Json.NET,我可以反序列化匿名类型,如下所示:

var token = JsonConvert.DeserializeAnonymousType(jsonStr, new { token = "" }).token;

新 namespace 中是否存在等效的方法?

最佳答案

作为 。 Net 5.0 System.Text.Json支持不可变类型(进而是匿名类型)的反序列化。从How to use immutable types and non-public accessors with System.Text.Json:

System.Text.Json can use a parameterized constructor, which makes it possible to deserialize an immutable class or struct. For a class, if the only constructor is a parameterized one, that constructor will be used.


由于匿名类型只有一个构造函数,因此它们现在可以成功反序列化。为此,请定义一个辅助方法,如下所示:
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
}
现在,您可以执行以下操作:
var token = JsonSerializerExtensions.DeserializeAnonymousType(jsonStr, new { token = "" }).token;
演示 fiddle here

关于c# - 使用System.Text.Json反序列化匿名类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59313256/

相关文章:

json - 将货币值从 JSON 转换为 NSDecimalNumber

json - Swift 4 可编码 : the keys are Int array in JSON data

.net-core - 在 MassTransit 消费者内部注入(inject)依赖项

c# - 最佳实践 : Adding a CLI to Existing Windows Service in . NET/Core

c# - 什么是 SUT,它从何而来?

c# - 在类中使用覆盖而不是事件订阅

c# - C# 中的正则表达式电子邮件验证器中的问题

PHP 警告 : json_encode() [<a href ='function.json-encode' >function. json-encode</a>]:参数中的 UTF-8 序列无效

c# - 如何传递对函数的引用

c# - 如何使用 EF Core 添加新表