C#如何将json转换为CSV

时间:2018-01-15 06:25:50

标签: c# json csv

我想编写一个程序将json转换为CSV 但是转换CSV有问题,因为我的列名包括数组,当我使用我的函数进行转换时,它有问题 例如: 这是我想转换的json:

{  
   "ref":"ABC123456",
   "pickcompname":"ABC Company",
   "gw":123.45,
   "packaing":[  
      {  
         "qty":5,
         "unit":"C",

      },
      {  
         "qty":7,
         "unit":"L",

      }
   ]
}

但我想让Packaing可以转换列名,如qty1,unit1,qty2,unit2,不幸的是,它只输出:

"ref",
"pickcompname",
"gw",
"commoditytype",
"packaing""ABC123456",
"ABC Company",
"123.45",
"D",
"[
    {
        "qty":5,
        "unit":"C"
    },
    {  
    "qty":7,
    "unit":"L",
    }
]"

如何修改它,这是我的C#代码:

    public string JsonToCsv3(string jsonContent, string delimiter)
    {

        var data = jsonStringToTable(jsonContent);
        var headers = ((IEnumerable<dynamic>)((IEnumerable<dynamic>)data).First()).Select((prop) => prop.Name).ToArray();
        var csvList = new List<string> 
        {
            string.Join(delimiter, headers.Select((prop) => string.Format(@"""{0}""", prop)).ToArray())
        };

        var lines = ((IEnumerable<dynamic>)data)
            .Select(row => row)
            .Cast<IEnumerable<dynamic>>()
            .Select((instance) => string.Join(delimiter, instance.Select((v) => string.Format(@"""{0}""", v.Value))))
            .ToArray();

        csvList.AddRange(lines);
        return string.Join(Environment.NewLine, csvList );
    }


    static private dynamic jsonStringToTable(string jsonContent)
    {
        var json = jsonContent.Split(new[] { '=' }).Last();
        return JsonConvert.DeserializeObject<dynamic>(json);
    }

    static private IEnumerable<T> jsonStringToTable<T>(string jsonContent) where T : class
    {
        var json = jsonContent.Split(new[] { '=' }).Last();
        return JsonConvert.DeserializeObject<IEnumerable<T>>(json);
    }

2 个答案:

答案 0 :(得分:0)

以下是使用Cinchoo ETL

执行此操作的方法
using (var p = new ChoJSONReader("sample16.json")
    .WithField("Ref", jsonPath: "$..ref", fieldType: typeof(string))
    .WithField("pickcompname", jsonPath: "$..pickcompname", fieldType: typeof(string))
    .WithField("gw", jsonPath: "$..gw", fieldType: typeof(double))
    .WithField("qty1", jsonPath: "$..packaing[0].qty", fieldType: typeof(int))
    .WithField("unit1", jsonPath: "$..packaing[0].unit", fieldType: typeof(string))
    .WithField("qty2", jsonPath: "$..packaing[1].qty", fieldType: typeof(int))
    .WithField("unit2", jsonPath: "$..packaing[1].unit", fieldType: typeof(string))
    )
{
    using (var c = new ChoCSVWriter("sample16.csv").WithFirstLineHeader())
        c.Write(p);
}

输出:

Ref,pickcompname,gw,qty1,unit1,qty2,unit2
ABC123456,ABC Company,123.45,5,C,7,L

答案 1 :(得分:0)

依赖于Newtonsoft.Json,这是一个给定CSV行数组的辅助方法,第一个是标题。

    public static IEnumerable<JObject> CsvToJson(IEnumerable<string> csvLines)
    {
        var csvLinesList = csvLines.ToList();

        var header = csvLinesList[0].Split(',');
        for (int i = 1; i < csvLinesList.Count; i++)
        {
            var thisLineSplit = csvLinesList[i].Split(',');
            var pairedWithHeader = header.Zip(thisLineSplit, (h, v) => new KeyValuePair<string, string>(h, v));

            yield return new JObject(pairedWithHeader.Select(j => new JProperty(j.Key, j.Value)));
        }
    }