3

我有一个从 Web 服务获取数据的小程序。该程序获取 JSON 响应,将其映射到 POCO 并将对象写入 CSV 文件(自动映射)。当我询问数据集中的“所有”数据时,它工作得很好,但是,如果我像这样查询资源(通过 OData):“$select EmpNo,FirstName,LastName”,CSV 编写器仍将写入所有列到 CSV 标题,例如“EmpNo、FirstName、LastName、Street、Address、City、Age”等,只需将 0(如果是 int)、false(如果是布尔值)或“”(如果是字符串)插入到没有数据。

Web 服务仅正确返回指定的列,因此这不是问题。我使用 CsvHelper 进行对象映射和 CSV 写入。(但我愿意使用任何可以解决我的问题的东西)

如果这是我在 OData 查询中要求的,我只想将“EmpNo,FirstName,LastName”和列的数据写入 CSV 文件。

解决这个问题有什么好主意吗?

4

2 回答 2

3

如果不知道您正在使用的确切代码,很难分辨。但我的猜测是,当您编写对象列表时,您正在使用其中包含额外字段的模型,这些字段都是空的,因为您没有通过 odata 请求它们。

如果您只需要 CsvHelper 的子集,您可能需要指定 aCsvClassMap<T>并将现有模型映射到您想要的字段

这里有很多关于 CsvClassMap 的示例:http: //joshclose.github.io/CsvHelper/

write 方法可能有一个方法重载,该方法将采用类映射。

于 2015-07-31T14:24:57.250 回答
0

You can create a ClassMapper and specify which properties from the object you want to write (and how you want to write them!)
https://joshclose.github.io/CsvHelper/examples/configuration/class-maps/mapping-properties

Then when you go to write, just specify the ClassMapper

using (var writer = new StreamWriter("path\\to\\file.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    csv.Configuration.RegisterClassMap<NameOfClassMapper>();
    csv.WriteRecords(records);
}
于 2020-09-17T21:36:44.660 回答