使用CSVHelper将JSON字符串转换为CSV
我正在我的ASP.NET Web API项目中使用JSON/CSV文件,并尝试使用 csvhelper 和 servicestack.text.text 库生成CSV,但无法正常工作。
包含数组的JSON文件是动态的,并且可能具有任意数量的字段。
我使用StreamReader读取文件,然后需要将其转换为CSV文件,以使其可供最终用户下载。
示例文件文本
[{"COLUMN1":"a","COLUMN2":"b","COLUMN3":"c","COLUMN4":"d","COLUMN5":"e"},
{"COLUMN1":"a","COLUMN2":"b","COLUMN3":"c","COLUMN4":"d","COLUMN5":"e"}]
json to csv
public static string jsonStringToCSV(string content)
{
var jsonContent = (JArray)JsonConvert.DeserializeObject(content);
var csv = ServiceStack.Text.CsvSerializer.SerializeToCsv(jsonContent);
return csv;
}
这不会导致我csv data
那么,某些文件是带有逗号或tab的界定类型,并且and I want to utilize CSVHelper to convert CSV string to an IEnumerable dynamically.
public static IEnumerable StringToList(string data, string delimiter, bool HasHeader)
{
using (var csv = new CsvReader(new StringReader(data)))
{
csv.Configuration.SkipEmptyRecords = true;
csv.Configuration.HasHeaderRecord = HasHeader;
csv.Configuration.Delimiter = delimiter;
var records = csv.GetRecords();
return records;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我能够通过使用
DeserializeObject
来解决它来解决它。用
制作CSV字符串。
用 WebAPI的最终用法
I was able to solve it by deserializing using
DeserializeObject
to a datatable.To convert JSON string to DataTable with Newtonsoft's Json.NET:
To make a CSV string with CSVHelper:
Final Usage in WebAPI
以防万一您想探索一个开源库来完成这项工作,这是我写的。
cinchoo etl使使用几行代码可将JSON转换为CSV,
以获取更多信息/来源,转到 https: //github.com/cinchoo/choetl
nuget软件包:
.net框架:
.net core:
样本小提琴: https://dotnetfiddle.net/t3u4w2
全面披露:我是该库的作者。
Just in case you want to explore an open-source library to do the job, here is one that I wrote.
Cinchoo ETL makes it easy to convert JSON to CSV with a few lines of code
For more information / source, go to https://github.com/Cinchoo/ChoETL
NuGet package:
.NET Framework:
.NET Core:
Sample fiddle: https://dotnetfiddle.net/T3u4W2
Full Disclosure: I'm the author of this library.
最近有同样的问题,我相信使用 system.dynamic.expandOobject 和 csvhelper 。它是较少的代码,希望与数据表相比性能相似或更好。
Had the same problem recently and I believe there is a little bit more elegant solution using the System.Dynamic.ExpandoObject and CsvHelper. It is less code and hopefully the performance is similar or better compared to the DataTable.
此代码对我来说是可以的:
3个功能(检查,解析和AUX)
This code is OK for me:
3 functions (check, parse and aux)
以下代码成功编译了最新稳定版本的CSVHelper Nuget软件包。
The below code successfully compiles with latest stable version of CsvHelper nuget package.