c#

时间:2016-03-29 03:37:30

标签: c# json csv csvhelper

我在我的asp.net网络API项目中使用JSON / CSV文件,并尝试使用CSVHelperServiceStack.Text库,但无法使其正常工作。

包含数组的JSON文件是动态的,可能包含任意数量的字段

我使用streamreader读取文件,然后需要将其转换为CSV文件,以便最终用户下载。

示例文件文字

[{"COLUMN1":"a","COLUMN2":"b","COLUMN3":"c","COLUMN4":"d","COLUMN5":"e"},
 {"COLUMN1":"a","COLUMN2":"b","COLUMN3":"c","COLUMN4":"d","COLUMN5":"e"}]

JSON到CSV

public static string jsonStringToCSV(string content)
{
    var jsonContent = (JArray)JsonConvert.DeserializeObject(content);

    var csv = ServiceStack.Text.CsvSerializer.SerializeToCsv(jsonContent);
    return csv;
}

这不会导致我的CSV数据

enter image description here

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

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

7 个答案:

答案 0 :(得分:30)

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

将JSON字符串转换为DataTable

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

制作CSV字符串

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

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;

答案 1 :(得分:9)

我不知道为你的问题报告解决方案是否为时已晚。如果你想探索开源库来完成这项工作,这里有一个

Cinchoo ETL可以轻松地将JSON转换为具有少量代码的csv

using (var r = new ChoJSONReader("sample.json"))
{
    using (var w = new ChoCSVWriter("sample.csv").WithFirstLineHeader())
    {
        w.Write(r);
    }
}

有关更多信息/来源,请转到https://github.com/Cinchoo/ChoETL

Nuget包:

.NET Framework:

      Install-Package ChoETL.JSON

.NET Core:

      Install-Package ChoETL.JSON.NETStandard

完全披露:我是这个图书馆的作者。

答案 2 :(得分:2)

string path = ""; // YOU .JSON PATH HERE
using (var r = new ChoJSONReader(path))
{
    using (var w = new ChoCSVWriter("csv_file_name_here.csv").WithFirstLineHeader())
    {
        w.Write(r);
    }
}

只需安装此软件包' ChoETL.JSON '

那你应该很好。祝你有美好的一天!

答案 3 :(得分:1)

最近也遇到了同样的问题,我相信使用System.Dynamic.ExpandoObjectCsvHelper会有更好的解决方案。它的代码更少,希望性能与DataTable相似或更好。

python setup.py develop

答案 4 :(得分:0)

public void Convert2Json() 
        { 
            try 
            { 
                if (FileUpload1.PostedFile.FileName != string.Empty) 
                { 
                    string[] FileExt = FileUpload1.FileName.Split('.'); 
                    string FileEx = FileExt[FileExt.Length - 1]; 
                    if (FileEx.ToLower() == "csv") 
                    { 
                        string SourcePath = Server.MapPath("Resources//" + FileUpload1.FileName); 
                        FileUpload1.SaveAs(SourcePath); 
                        string Destpath = (Server.MapPath("Resources//" + FileExt[0] + ".json")); 

                        StreamWriter sw = new StreamWriter(Destpath); 
                        var csv = new List<string[]>(); 
                        var lines = System.IO.File.ReadAllLines(SourcePath); 
                        foreach (string line in lines) 
                            csv.Add(line.Split(',')); 
                        string json = new 
                            System.Web.Script.Serialization.JavaScriptSerializer().Serialize(csv); 
                        sw.Write(json); 
                        sw.Close(); 
                        TextBox1.Text = Destpath; 
                        MessageBox.Show("File is converted to json."); 
                    } 
                    else 
                    { 
                        MessageBox.Show("Invalid File"); 
                    } 

                } 
                else 
                { 
                    MessageBox.Show("File Not Found."); 
                } 
            } 
            catch (Exception ex) 
            { 
                MessageBox.Show(ex.Message); 
            } 
        }

答案 5 :(得分:0)

export const signUp = user => dispatch => {
    dispatch(startSubmit('sign-up'));
    return authAPI.signUp(user).then (user => {

        dispatch(setUser(user));

        dispatch(setNotify({open: true, content: 'Some content', type: 
       'success'}));

        dispatch(stopSubmit('sign-up'));

        }).catch(({response: {data}}) => {

        let notification = null;

        if ( data.messageList && data.messageList.length >= 0 ) {
            notification = {content: data.messageList[0], open: true, type: 
            'error'};

            dispatch (setNotify(notification));

            return data.messageList;
        }
        dispatch(stopSubmit('sign-up'));
    })
};

答案 6 :(得分:0)

这个代码对我来说没问题:

3 个函数(检查、解析和辅助)

    private bool IsValidJson(string strInput)
    {
        try 
        { 
            if (string.IsNullOrWhiteSpace(strInput)) { return false; }
        
            strInput = strInput.Trim();

            if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || (strInput.StartsWith("[") && strInput.EndsWith("]"))) 
            {
                try
                {
                    _ = JToken.Parse(strInput);

                    return true;
                }
                catch
                {
                    return false;
                }
            }

            return false;
        }
        catch { throw; }
    }

    private string ParseJsonToCsv(string json)
    {
        try
        {
            XmlNode xml = JsonConvert.DeserializeXmlNode("{records:{record:" + json + "}}");

            XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(xml.InnerXml);

            DataSet dataSet = new DataSet(); dataSet.ReadXml(new XmlNodeReader(xmldoc));

            string csv = DTableToCsv(dataSet.Tables[0], ",");

            return csv;
        }
        catch { throw; }
    }

    private string DTableToCsv(DataTable table, string delimator)
    {
        try 
        { 
            var result = new StringBuilder();

            for (int i = 0; i < table.Columns.Count; i++)
            {
                result.Append(table.Columns[i].ColumnName);
                result.Append(i == table.Columns.Count - 1 ? "\n" : delimator);
            }

            foreach (DataRow row in table.Rows)
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    result.Append(row[i].ToString());
                    result.Append(i == table.Columns.Count - 1 ? "\n" : delimator);
                }

            return result.ToString().TrimEnd(new char[] { '\r', '\n' });
        }
        catch { throw; }
    }