Convert nested JSON to CSV

前端 未结 2 752
悲哀的现实
悲哀的现实 2021-02-15 02:46

I am converting a nested JSON object with more than 10 levels to CSV file in C# .NET.

I have been using JavaScriptSerializer().Deserialize(json)

2条回答
  •  独厮守ぢ
    2021-02-15 03:46

    I wrote this and it is working for me Here we save all breadcrumps of object tree in headers with format prop_prop And save jarray property objects in headers in format prop1

        public Dictionary ComplexJsonToDictionary(JObject jObject, Dictionary result, string field)
        {
            foreach (var property in jObject.Properties())
            {
                var endField = field + (string.IsNullOrEmpty(field) ? "" : "_") + property.Name;
    
                var innerDictionary = new Dictionary();
                try
                {
                    var innerValue = JObject.Parse(Convert.ToString(property.Value));
    
    
                    result.AddOrOverride(ComplexJsonToDictionary(innerValue, innerDictionary, endField));
                }
                catch (Exception)
                {
                    try
                    {
                        var innerValues = JArray.Parse(Convert.ToString(property.Value));
                        try
                        {
                            var i = 0;
                            foreach (var token in innerValues)
                            {
                                var innerValue = JObject.Parse(Convert.ToString(token));
    
                                result.AddOrOverride(ComplexJsonToDictionary(innerValue, innerDictionary, endField+i++));
                            }
                        }
                        catch (Exception)
                        {
                            result.Add(endField, string.Join(",", innerValues.Values()));
                        }
                    }
                    catch (Exception)
                    {
                        result.Add(endField, property.Value.ToString());
                    }
                }
            }
            return result;
        }
    

    Thanks for atantion and please write review if appropriate.

提交回复
热议问题