JSON string to CSV and CSV to JSON conversion in c#

前端 未结 6 614
滥情空心
滥情空心 2020-11-28 08:01

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 con

6条回答
  •  爱一瞬间的悲伤
    2020-11-28 08:48

    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(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;
    

提交回复
热议问题