JSON 字符串到 CSV 和 CSV 到 JSON 转换在 C# [英] JSON string to CSV and CSV to JSON conversion in c#

查看:71
本文介绍了JSON 字符串到 CSV 和 CSV 到 JSON 转换在 C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的 asp.net Web API 项目中处理 JSON/CSV 文件并尝试使用

然后一些文件是带逗号或制表符的分隔符类型,我想利用 CSVHelper 来转换 CSV字符串到 IEnumerable 动态

public static IEnumerable StringToList(string data, string delimiter, bool HasHeader){使用 (var csv = new CsvReader(new StringReader(data))){csv.Configuration.SkipEmptyRecords = true;csv.Configuration.HasHeaderRecord = HasHeader;csv.Configuration.Delimiter = 分隔符;var 记录 = csv.GetRecords();退货记录;}}

解决方案

我能够使用 Json.net 通过 DeserializeObject 将其解决到数据表中,所以想发布我自己的答案但不会将其标记为已接受,如果有人的话有更好的方法来做到这一点.

将JSON字符串转换为DataTable

public static DataTable jsonStringToTable(string jsonContent){DataTable dt = JsonConvert.DeserializeObject(jsonContent);返回 dt;}

制作CSV字符串

public static string jsonToCSV(string jsonContent, string delimiter){StringWriter csvString = new StringWriter();使用 (var csv = new CsvWriter(csvString)){csv.Configuration.SkipEmptyRecords = true;csv.Configuration.WillThrowOnMissingField = false;csv.Configuration.Delimiter = 分隔符;使用 (var dt = jsonStringToTable(jsonContent)){foreach(dt.Columns 中的 DataColumn 列){csv.WriteField(column.ColumnName);}csv.NextRecord();foreach(dt.Rows 中的 DataRow 行){for (var i = 0; i < dt.Columns.Count; i++){csv.WriteField(row[i]);}csv.NextRecord();}}}返回 csvString.ToString();}

Web API 中的最终使用

string csv = jsonToCSV(content, ",");HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);result.Content = new StringContent(csv);result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "export.csv" };返回结果;

I'm working with JSON/CSV files in my asp.net web API project and tried with CSVHelper and ServiceStack.Text libraries but couldn't make it work.

The JSON file containing an array is dynamic and may have any number of fields

I read the file using streamreader and then need to convert it into CSV file to make it downloadable for end users.

example file text

[{"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;
}

This doesn't result me CSV data

Then some files are delimiter type with comma or tab and and i want to utilize CSVHelper to convert CSV string to 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;
     }
}

解决方案

I was able to solve it by DeserializeObject to a datatable using Json.net, so want to post my own answer but will not mark it as accepted, if anyone have better way to do this.

To convert JSON string to DataTable

public static DataTable jsonStringToTable(string jsonContent)
        {
            DataTable dt = JsonConvert.DeserializeObject<DataTable>(jsonContent);
            return dt;
        }

To make CSV string

public static string jsonToCSV(string jsonContent, string delimiter)
        {
            StringWriter csvString = new StringWriter();
            using (var csv = new CsvWriter(csvString))
            {
                csv.Configuration.SkipEmptyRecords = true;
                csv.Configuration.WillThrowOnMissingField = false;
                csv.Configuration.Delimiter = delimiter;

                using (var dt = jsonStringToTable(jsonContent))
                {
                    foreach (DataColumn column in dt.Columns)
                    {
                        csv.WriteField(column.ColumnName);
                    }
                    csv.NextRecord();

                    foreach (DataRow row in dt.Rows)
                    {
                        for (var i = 0; i < dt.Columns.Count; i++)
                        {
                            csv.WriteField(row[i]);
                        }
                        csv.NextRecord();
                    }
                }
            }
            return csvString.ToString();
        }

Final Usage in Web API

string csv = jsonToCSV(content, ",");

                HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
                result.Content = new StringContent(csv);
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
                result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "export.csv" };
                return result;

这篇关于JSON 字符串到 CSV 和 CSV 到 JSON 转换在 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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