c# - 如何使用 System.Text.Json 将 ReadOnlySpan<char> 反序列化为对象

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

我有一个案例,当我得到一个非常大的文本数据并且每一行都包含一些元数据 + json 数据字符串。 我需要处理每一行的 json 数据。

这是我的:

public Data GetData(string textLine)
{
    var spanOfLine = textLine.AsSpan();
    var indexOfComma = spanOfLine.IndexOf(":");
    var dataJsonStringAsSpan = spanOfLine.Slice(indexOfComma + 1);

    // now use dataJsonStringAsSpan which is ReadOnlySpan<char> to deserialize the Data
}

其中 Data 是一个 Dto 类,它具有一堆 (7) 个不同的属性:

public class Data
{
    public int Attribute1 { get; set; }

    public double Attribute2 { get; set; }
    // ... more properties, emitted for the sake of brevity
}

我正在尝试通过 System.Text.Json 实现这一目标应用程序接口(interface)。令人惊讶的是,它没有任何可从 ReadOnlySpan<char> 反序列化的重载。 ,所以我想出了这个:

public Data GetData(string textLine)
{
    var spanOfLine = textLine.AsSpan();
    var indexOfComma = spanOfLine.IndexOf(":");
    var dataJsonStringAsSpan = spanOfLine.Slice(indexOfComma + 1);

    var byteCount = Encoding.UTF8.GetByteCount(dataJsonStringAsSpan);
    Span<byte> buffer = stackalloc byte[byteCount];
    Encoding.UTF8.GetBytes(dataJsonStringAsSpan, buffer);
    var data = JsonSerializer.Deserialize<Data>(buffer);
    return data;
}

虽然这可行,但看起来非常复杂。

这是要走的路还是我错过了更简单的东西?

最佳答案

.Net6 支持 Deserialize(ReadOnlySpan<Char> , show ref

例子

  ReadOnlySpan<char> jsonString = "....";

  WeatherForecast? weatherForecast = JsonSerializer.Deserialize<WeatherForecast>(jsonString);

在线Example

关于c# - 如何使用 System.Text.Json 将 ReadOnlySpan<char> 反序列化为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58845880/

相关文章:

c# - 有没有办法防止 Visual Studio 2008 Designer 在代码和设计窗口之间跳转时始终重绘窗口?

c# - 将 DataGrid 的 FontWeight 属性绑定(bind)到值转换器

c# - WebBrowser 文本选择更改时触发事件

元素中带有分号的 MySQL JSON 路径

php - 从公共(public) Google 日历获取 JSON

asp.net-core - ASP.NET Core App 中 project.json 中 build 选项下的 preserveCompilationContext 有什么用?

c# - 网络核心 API : Assigning Array name and showing in Angular

javascript - 通过 REST API 的 Google 跟踪代码管理器 (GTM) 数据层

javascript - 如何将javascript对象映射到mvc模型?

c# - ASP.Net Core Web API 捕获用于日志记录的 HTTP 请求