使用 C# 将 csv 文件转换为 json [英] Converting a csv file to json using C#

查看:55
本文介绍了使用 C# 将 csv 文件转换为 json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人编写了使用 C# 将 CSV 文件转换为 Json 的实用程序.从上一个关于 stackoverflow 的问题中,我知道这个不错的实用程序 - https://github.com/cparker15/csv-to-json 目前我打算参考它,但现有的 C# 实现会非常有帮助!谢谢!

I was wondering if someone's written a utility to convert a CSV file to Json using C#. From a previous question on stackoverflow, I'm aware of this nice utility - https://github.com/cparker15/csv-to-json and at the moment I plan to refer to it but an existing C# implementation would be very helpful! Thanks!

推荐答案

如果你可以使用 System.Web.Extensions,这样的事情可以工作:

If you can use System.Web.Extensions, something like this could work:

var csv = new List<string[]>(); // or, List<YourClass>
var lines = System.IO.File.ReadAllLines(@"C:file.txt");
foreach (string line in lines)
    csv.Add(line.Split(',')); // or, populate YourClass          
string json = new 
    System.Web.Script.Serialization.JavaScriptSerializer().Serialize(csv);

您可能对 csv 文件有更复杂的解析要求,并且您可能有一个封装一行数据的类,但重点是一旦您有了行集合,就可以用一行代码序列化为 JSON.

You might have more complex parsing requirements for the csv file and you might have a class that encapsulates the data from one line, but the point is that you can serialize to JSON with one line of code once you have a Collection of lines.

这篇关于使用 C# 将 csv 文件转换为 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆