如何使用C#将Json文件转换为Csv文件 [英] How Can I Convert A Json File To Csv File Using C#

查看:105
本文介绍了如何使用C#将Json文件转换为Csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有json文件,我必须将该json文件转换为csv并将其存储在某处,

和json具有嵌套属性。

{AlertID: 20515, AlertIDSpecified:真 AlertSentTimeStamp: \ /日期(-2208992400000)\ /, AlertSentTimeStampSpecified:真 AlertedUsers:[], AttributeDetails:{ 的缩写:状态, 数据类型: 串, DefaultOperator: =, DefaultStatus:4 DefaultStatusSpecified:真 DisplayName的: 状态, EffectiveStatus:4 EffectiveStatusSpecified:真, HelpText:表示检查执行的状态,ID:10400,IDSpecified:true,IsQualifier}}

如上所述。

如何将json文件转换为csv?



i have json file and i have to convert that json file into csv and store it some where,
and json has nested attributes.
{"AlertID":20515,"AlertIDSpecified":true,"AlertSentTimeStamp":"\/Date(-2208992400000)\/","AlertSentTimeStampSpecified":true,"AlertedUsers":[],"AttributeDetails":{"Abbreviation":"Status","DataType":"string","DefaultOperator":"=","DefaultStatus":4,"DefaultStatusSpecified":true,"DisplayName":"Status","EffectiveStatus":4,"EffectiveStatusSpecified":true,"HelpText":"Indicates the status of the check execution","ID":10400,"IDSpecified":true,"IsQualifier}}
like the above one.
how can i convert that json file into csv?

string text = System.IO.File.ReadAllText("input.txt");
            XmlNode xml = JsonConvert.DeserializeXmlNode("{records:{record:" + text + "}}"); 
            XmlDocument xmldoc = new XmlDocument();
            //Create XmlDoc Object
            xmldoc.LoadXml(xml.InnerXml);
            //Create XML Steam 
            var xmlReader = new XmlNodeReader(xmldoc);
            DataSet dataSet = new DataSet();
            //Load Dataset with Xml
            dataSet.ReadXml(xmlReader);
            //return single table inside of dataset
            var csv = dataSet.Tables[0].getCSV(",");
        }
        public static string getCSV(this DataTable table,string delimitor)
      {
            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" : delimitor);
            }
        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" : delimitor);
        }
        }
        return result.ToString().TrimEnd(new char[] { '\r', '\n' });
        //return result.ToString();
      }



i得到了这个代码,但它不起作用。

可以帮助我做这个吗?



在此先感谢

Suresh gaddam


i got this code some where but it is not working.
can any one help me out in doing this?

Thanks in Advance
Suresh gaddam

推荐答案

我尝试了一些东西像这样,请根据您的使用情况进行更改:

I have tried something like this , Please alter according to your usage:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.IO;


namespace WindowsFormsApplication1
{
    public class AlteredUsers
    {
        public int UserID;
        public string userName;
    }
    public class AttributeDetails
    {
        public string Abbreviation;
        public string DataType;
        public string DefaultOperator;
        public int DefaultStatus;
        public bool DefaultStatusSpecified;
        public string DisplayName;
        public int EffectiveStatus;
        public bool EffectiveStatusSpecified;
        public string HelpText;
        public int ID;
        public bool IDSpecified;
        public bool IsQualifier;

    }
    public class MyJSONClass
    {
        public int AlertID;
        public bool AlertIDSpecified;
        public string AlertSentTimeStamp;
        public bool AlertSentTimeStampSpecified;
        public List<AlteredUsers> Altereduser;
        public AttributeDetails Attributedetails;
        
    }
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnConvertToCsv_Click(object sender, EventArgs e)
        {
            MyJSONClass objMyJSONClass = new MyJSONClass();
            objMyJSONClass.Altereduser = new List<AlteredUsers>();
            objMyJSONClass = ConvertJSONToObject(textBox1.Text);
            if (null != objMyJSONClass)
            {
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "CSV File|*.csv";
                saveFileDialog1.Title = "Save CSV File";
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    SaveToCSV(saveFileDialog1.FileName, objMyJSONClass);
                }
            }
        }

        private void SaveToCSV(string csvfileName, MyJSONClass objMyJSONClass)
        {
            string csvString = objMyJSONClass.AlertID+","+
                objMyJSONClass.AlertIDSpecified+","+
                objMyJSONClass.AlertSentTimeStamp+","+
                objMyJSONClass.AlertSentTimeStampSpecified;

            if (null != objMyJSONClass.Altereduser)
            {
                foreach (AlteredUsers user in objMyJSONClass.Altereduser)
                {
                    csvString = "," + user.UserID.ToString() + "," + user.userName;
                }
            }

            csvString = csvString + "," + objMyJSONClass.Attributedetails.Abbreviation + "," +
                        objMyJSONClass.Attributedetails.DataType + "," +
                        objMyJSONClass.Attributedetails.DefaultOperator + "," +
                        objMyJSONClass.Attributedetails.DefaultStatus.ToString() + "," +
                        objMyJSONClass.Attributedetails.DefaultStatusSpecified.ToString() + "," +
                        objMyJSONClass.Attributedetails.DisplayName + "," +
                        objMyJSONClass.Attributedetails.EffectiveStatus.ToString() + "," +
                        objMyJSONClass.Attributedetails.EffectiveStatusSpecified.ToString() + "," +
                        objMyJSONClass.Attributedetails.HelpText + "," +
                        objMyJSONClass.Attributedetails.ID.ToString() + "," +
                        objMyJSONClass.Attributedetails.IDSpecified.ToString() + "," +
                        objMyJSONClass.Attributedetails.IsQualifier.ToString();


            File.WriteAllText(csvfileName, csvString);
        }

        private MyJSONClass ConvertJSONToObject(string InputJSONString)
        {
            MyJSONClass objMyJSONClass = new MyJSONClass();
            objMyJSONClass.Altereduser = new List<AlteredUsers>();

            try
            {
                objMyJSONClass = (MyJSONClass)JsonConvert.DeserializeObject(InputJSONString, objMyJSONClass.GetType());

                return objMyJSONClass;
            }
            catch (Exception ex)
            {

                return null;
            }
            
        }
    }
}





请更正你的JSON喜欢这个:





{

AlertID:20515,

AlertIDSpecified:true,

AlertSentTimeStamp:日期(-2208992400000),

AlertSentTimeStampSpecified:true,

AlertedUsers:[],

AttributeDetails:

{

缩写:状态,

DataType:string,

DefaultOperator:=,

DefaultStatus:4,

DefaultStatusSpecified :true,

DisplayName:状态,

EffectiveStatus:4,

EffectiveStatusSpecified:true,

HelpText:表示支票执行的状态,

ID:10400,

IDSpecified:true,

IsQualifier:true

}

}



please correct your JSON Like this :


{
"AlertID":20515,
"AlertIDSpecified":true,
"AlertSentTimeStamp":"Date(-2208992400000)",
"AlertSentTimeStampSpecified":true,
"AlertedUsers":[],
"AttributeDetails":
{
"Abbreviation":"Status",
"DataType":"string",
"DefaultOperator":"=",
"DefaultStatus":4,
"DefaultStatusSpecified":true,
"DisplayName":"Status",
"EffectiveStatus":4,
"EffectiveStatusSpecified":true,
"HelpText":"Indicates the status of the check execution",
"ID":10400,
"IDSpecified":true,
"IsQualifier":true
}
}


这篇关于如何使用C#将Json文件转换为Csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆