簡體   English   中英

C#如何將json轉換為CSV

[英]C# how to convert json to 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);
    }

這是使用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

依賴於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)));
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM