是否可以将流集合直接反序列化到字典中?而不是使用 ToDictionary
Is it possible to de-serialize a stream collection directly into a dictionary? instead of using ToDictionary
我有这个简单的股票和价格集合:
[
{ "name": "AABA", "price": 60.6808},
{ "name": "AAL", "price": 33.3216}
]
库存class:
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);
不,这不是字典的正确形状。您已经在做的是 IMO 正确的方法。您 可以 尝试编写自定义反序列化来避免一个步骤,但这是一项 很多 的工作,并且有很多引入错误的机会,与您现有的相比,它将正常工作。
我有这个简单的股票和价格集合:
[
{ "name": "AABA", "price": 60.6808},
{ "name": "AAL", "price": 33.3216}
]
库存class:
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);
不,这不是字典的正确形状。您已经在做的是 IMO 正确的方法。您 可以 尝试编写自定义反序列化来避免一个步骤,但这是一项 很多 的工作,并且有很多引入错误的机会,与您现有的相比,它将正常工作。