C#将Json转换为CSV

时间:2018-05-14 04:37:07

标签: c# json csv

我有一个json文件,格式如下:

{
"HDRDTL":["SRNO","STK_IDN","CERTIMG"],
"PKTDTL":[
{"SRNO":"2814","STK_IDN":"1001101259","CERTIMG":"6262941723"},
{"SRNO":"2815","STK_IDN":"1001101269","CERTIMG":"6262941726"},
{"SRNO":"2816","STK_IDN":"1001101279","CERTIMG":"6262941729"}
],
"IMGTTL":
["CERTIMG","ARRIMG"],
"IMGDTL":{"CERTIMG":"CRd6z2uq3gvx7kk","ARRIMG":"ASd6z2uq3gvx7kk"}
}

“PKTDTL”数组是我需要转换为csv的部分。 我怎样才能在C#中实现这个目标?

注意,作为一个例子,我在“PKTDTL”中只有3个项目,真正的json文件有数千行({“SRNO”...})并且很大。

我写了下面的代码但是没有用。请参阅代码中注释的错误消息。

问题

  • 任何人都知道失败的原因?
  • 你有更好的/替代方法

    public static void ConvertJsonToCSV(string InFile)
    {
    
    string OutFile=InFile.Replace("json","csv");
    
    StreamReader sInFile = new StreamReader(InFile);
    StreamWriter sOutFile = new StreamWriter(OutFile);
    
    using (sInFile)
    {
        string sJson = sInFile.ReadToEnd();
    
        //*************************************************************
        // the below line failed, error message: unexpected json token
        // when reading datatable, expected startArray, got StartObject.
        //**************************************************************
    
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(sJson);
        //DataTable dt = JsonConvert.DeserializeAnonymousType(sJson, new { Makes = default(DataTable) }).Makes;
    
        var sb = new StringBuilder();
    
        string[] columnNames = (from dc in dt.Columns.Cast<DataColumn>()
                                select dc.ColumnName).ToArray();
    
        sb.AppendLine(string.Join(",", columnNames));
    
        foreach (DataRow dr in dt.Rows)
        {
            foreach (object field in dr.ItemArray)
            {
                sb.Append(field.ToString().Replace(",", "") + ",");
            }
            sb.Replace(",", "\n", sb.Length - 1, 1);
        }
    
        sOutFile.Write(sb.ToString());
    
        sOutFile.Close();
        sInFile.Close();
    }
    

    }

3 个答案:

答案 0 :(得分:1)

我发现自己处于类似情况。这就是我做的。首先我创建了一个JObject(使用Newtonsoft.Json.Linq),让我们考虑一下你的json是一个名为“strJSON”的字符串变量。

 JObject jsonObj= JObject.parse(strJSON);
 JObject  PKTDL=jsonObj["PKTDTL"] as JObject;
 IList<string> keys = PKTDL.Properties().Select(p => p.Name).ToList(); // this gives column names
 StringBuilder sb=new StringBuilder();
 string headers="";
 foreach(string key in keys)
 {
   headers+=","+key;
 }  
 sb.AppendLine(headers.TrimStart(','));
 foreach(JObject j in jsonObj["PKTDTL"]) //if jobject doesnt work try "JToken j"
 {
    string values="";
    foreach(string key in keys)
    {
       values+=","+jsonObj["PKTDTL"][key];
    }
    sb.AppendLine(values.TrimStart(','));
 }

   File.WriteAllText(filePath, sb.ToString());

然后将sb保存为csv

答案 1 :(得分:1)

使用Cinchoo ETL - 一个开源库,您可以使用几行代码轻松完成转换

string json = @"{
    ""HDRDTL"":[""SRNO"",""STK_IDN"",""CERTIMG""],
    ""PKTDTL"":[
    {""SRNO"":""2814"",""STK_IDN"":""1001101259"",""CERTIMG"":""6262941723""},
    {""SRNO"":""2815"",""STK_IDN"":""1001101269"",""CERTIMG"":""6262941726""},
    {""SRNO"":""2816"",""STK_IDN"":""1001101279"",""CERTIMG"":""6262941729""}
    ],
    ""IMGTTL"":
    [""CERTIMG"",""ARRIMG""],
    ""IMGDTL"":{""CERTIMG"":""CRd6z2uq3gvx7kk"",""ARRIMG"":""ASd6z2uq3gvx7kk""}
    }";

StringBuilder sb = new StringBuilder();
using (var p = ChoJSONReader.LoadText(json).WithJSONPath("$..PKTDTL")
    )
{
    using (var w = new ChoCSVWriter(sb)
        .WithFirstLineHeader()
        )
        w.Write(p);
}

Console.WriteLine(sb.ToString());

输出:

SRNO,STK_IDN,CERTIMG
2814,1001101259,6262941723
2815,1001101269,6262941726
2816,1001101279,6262941729

Checkout CodeProject文章提供了一些额外的帮助。

免责声明:我是这个图书馆的作者。

答案 2 :(得分:0)

duplicate类似的问题(请参见那里的JsonToCsv(string,string)方法)。如果您已经在使用NewtonSoft Json.NETCsvHelper,则可以在ExpandoObject的帮助下进行类似的转换。

    var jsonText = @"{
        ""HDRDTL"":[""SRNO"",""STK_IDN"",""CERTIMG""],
        ""PKTDTL"":[
        {""SRNO"":""2814"",""STK_IDN"":""1001101259"",""CERTIMG"":""6262941723""},
        {""SRNO"":""2815"",""STK_IDN"":""1001101269"",""CERTIMG"":""6262941726""},
        {""SRNO"":""2816"",""STK_IDN"":""1001101279"",""CERTIMG"":""6262941729""}
        ],
        ""IMGTTL"":
        [""CERTIMG"",""ARRIMG""],
        ""IMGDTL"":{""CERTIMG"":""CRd6z2uq3gvx7kk"",""ARRIMG"":""ASd6z2uq3gvx7kk""}
        }";

    var jtoken = JObject.Parse(jsonText).SelectToken("$..PKTDTL");
    var expandos = jtoken.ToObject<ExpandoObject[]>();
    string csvText;

    using (var writer = new StringWriter())
    {
        using (var csv = new CsvWriter(writer))
        {
            csv.WriteRecords(expandos as IEnumerable<dynamic>);
        }

        csvText = writer.ToString();
    }

    Console.WriteLine(csvText);