【问题标题】:Is it possible to de-serialize a stream collection directly into a dictionary? instead of using ToDictionary是否可以将流集合直接反序列化到字典中?而不是使用 ToDictionary
【发布时间】:2021-04-25 20:01:08
【问题描述】:

我有这个简单的股票和价格集合:

[
    { "name": "AABA", "price": 60.6808},
    { "name": "AAL", "price": 33.3216}
]

股票类:

public class Stock
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

我的目标是将流直接反序列化为 IDictinary,其中键是 Name,值是 Stock(出于性能原因),我只能通过反序列化流来做到这一点转换成IEnumerable<Stock>,然后将其转换为字典:

using (stream)
{
    IDictinary<string, Stock> = await System.Text.Json.JsonSerializer
            .DeserializeAsync<IEnumerable<Stock>>(stream.BaseStream, 
                new JsonSerializerOptions() { PropertyNameCaseInsensitive = false }, 
            ct); 
}

我能够做到这一点的唯一方法是在末尾添加ToDictionary(x =&gt; x.Name, x =&gt; new Stock() { Name = x.Name, Price = x.Price })

是否可以直接将流作为字典读取?

喜欢:

    IDictinary<string, Stock> = await System.Text.Json.JsonSerializer
            .DeserializeAsync<IDictinary<string, Stock>>(stream.BaseStream, 
                new JsonSerializerOptions() { PropertyNameCaseInsensitive = false }, 
            ct); 

【问题讨论】:

  • ToDictionary(x =&gt; x.Name, x =&gt; x) 至少可以让您重用现有的Stock 对象,而不是构建新的对象

标签: c# .net-core stream deserialization


【解决方案1】:

不,这不是字典的正确形状。您已经在做的是 IMO 正确的方法来做到这一点。您可以尝试编写自定义反序列化来避免步骤,但与您已有的相比,这是一项大量工作,并且有很多机会引入错误这将正常工作。

【讨论】:

    猜你喜欢
    • 2023-03-09
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    • 2016-05-27
    • 2016-03-12
    • 2018-03-23
    • 1970-01-01
    相关资源
    最近更新 更多