【发布时间】: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 => x.Name, x => 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 => x.Name, x => x)至少可以让您重用现有的Stock对象,而不是构建新的对象
标签: c# .net-core stream deserialization