Click here to Skip to main content
15,174,684 members
Articles / Programming Languages / XML
Posted 22 Mar 2013

Tagged as


13 bookmarked

Create CSV from JSON in C#

Rate me:
Please Sign up or sign in to vote.
4.84/5 (16 votes)
19 Mar 2017CPOL
Using Extension Method and JSON Serializer


I faced a problem of creating CSV from a JSON object in ASP.NET. Here I am showing how to convert JSON to CSV with XML and DataSet.

Using the Code

I am using an Extension method of DataTable to create CSV, XmlNodeReader to create XML from an XML node, JSON.DeserializeXmlNode. Let's start work:

var json={
"employees": [
{ "firstName":"John" , "lastName":"Doe" }, 
{ "firstName":"Anna" , "lastName":"Smith" }, 
{ "firstName":"Peter" , "lastName":"Jones" }

I need it deserialized first:

XmlNode xml = JSON.DeserializeXmlNode("{records:{record:" + json + "}}"); 
XmlDocument xmldoc = new XmlDocument();
//Create XmlDoc Object
//Create XML Steam 
var xmlReader = new XmlNodeReader(xmldoc);
DataSet dataSet = new DataSet();
//Load Dataset with Xml
//return single table inside of dataset
var csv = dataSet.Tables[0].ToCSV(",");

You have found that here is the extension method .ToCSV. Let's see how to create this.

public static string ToCSV(this DataTable table,string delimator)
    var result = new StringBuilder();
    for (int i = 0; i < table.Columns.Count; i++)
        result.Append(i == table.Columns.Count - 1 ? "\n" : delimator);
    foreach (DataRow row in table.Rows)
        for (int i = 0; i < table.Columns.Count; i++)
            result.Append(i == table.Columns.Count - 1 ? "\n" : delimator);
    return result.ToString().TrimEnd(new char[] { '\r', '\n' });
    //return result.ToString();

This is it. Thanks!

Here, you will see how to convert string to ObjectList, Object to Json string.

Using C# JavascriptSerializer Class

public static class Helper
    public static string AsJsonList<T>(List<T> tt)
        return new JavaScriptSerializer().Serialize(tt);
    public static string AsJson<T>(T t)
        return new JavaScriptSerializer().Serialize(t);
    public static List<T> AsObjectList<T>(string tt)
        return new JavaScriptSerializer().Deserialize<List<T>>(tt);
    public static T AsObject<T>(string t)
        return new JavaScriptSerializer().Deserialize<T>(t);

It will help you create Json from datatable.

public string DataTableToJsonObj(DataTable dt)
    DataSet ds = new DataSet();
    StringBuilder JsonString = new StringBuilder();
    if (ds != null && ds.Tables[0].Rows.Count > 0)
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                if (j < ds.Tables[0].Columns.Count - 1)
                    JsonString.Append("\"" + 
                    ds.Tables[0].Columns[j].ColumnName.ToString() + 
                    "\":" + "\"" + 
                    ds.Tables[0].Rows[i][j].ToString() + "\",");
                else if (j == ds.Tables[0].Columns.Count - 1)
                    JsonString.Append("\"" + 
                    ds.Tables[0].Columns[j].ColumnName.ToString() + 
                    "\":" + "\"" + 
                    ds.Tables[0].Rows[i][j].ToString() + "\"");
            if (i == ds.Tables[0].Rows.Count - 1)
        return JsonString.ToString();
        return null;

Using any approach, let's just use it... you are fine.

For creating CSV, I would suggest you to use Nuget Package.

Install-Package ServiceStack.Text



string JsonSerializer.SerializeToString<T>(T value)
void JsonSerializer.SerializeToWriter<T>(T value, TextWriter writer)

T JsonSerializer.DeserializeFromString<T>(string value)
T JsonSerializer.DeserializeFromReader<T>(TextReader reader)


string TypeSerializer.SerializeToString<T>(T value)
void TypeSerializer.SerializeToWriter<T>(T value, TextWriter writer)

T TypeSerializer.DeserializeFromString<T>(string value)
T TypeSerializer.DeserializeFromReader<T>(TextReader reader)


string CsvSerializer.SerializeToString<T>(T value)
void CsvSerializer.SerializeToWriter<T>(T value, TextWriter writer)

T CsvSerializer.DeserializeFromString<T>(string value)
T CsvSerializer.DeserializeFromReader<T>(TextReader reader)


Happy coding, folks!

Hope all of you comments on issues that you are having. It's up to you to choose which approach you will use.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Yaseer Arafat
Software Developer (Senior) Individual Consultant
Bangladesh Bangladesh
• Experience in analysis, design and development of client/server, web based and n- tier application. Expert in developing windows applications, web applications, windows services and web services in Microsoft Visual Studio .Net IDE using C#.Net 1.1, C#.Net 2.0, VB.NET, ASP.NET, ADO.NET and SQL Server.
• Proficient in Web Services, SOAP, XML, XSL, XSLT, Xpath, XSL-FO, XPointer, DTD, XML Schema, CSS, DOM, HTML, AJAX and JavaScript, JQuery.
• Created deployment packages for Applications using Visual studio.Net Startup Project, which involves creating native image of an assembly, installing an assembly in Global assembly cache (GAC)
• Worked extensively with Data Adapter, Dataset, Data reader as a part of ADO.NET to access and Update database.
• Extensive experience in SQL Server Database design, Database maintenance, developing T-SQL queries, stored procedures, and triggers using SQL Server 2000/2005/2008.
• Good working knowledge with designer tools such as Microsoft Visio.
• Good working knowledge in designing Use Case, Class, Sequence, Collaboration, State,
Component, Deployment, Activity diagrams using UML
• Expertise in designing UML design patterns such as Adapter, Proxy, Bridge, and Facade and so on
• Expert in dealing with Private, Shared satellite and resource assemblies, configuring them with strong names, Deploying in GAC
• Expert in debugging an application using the debugging tools provided by the Visual Studio.Net IDE.
• Functional domain experience involves Financial, Telecom and Hospital management.
• Effective in working independently and collaboratively in teams.

Specialties:C#.NET,ASP.NET,ASP.NET MVC3,EnityFramework,JQuery,Linq to SQL,Oracle11g,TSQL,HTML,CSS,DevExpress,Crystal Reports.

Linkedin Profile

Comments and Discussions

GeneralMy vote of 5 Pin
Karthik_Mahalingam21-Mar-17 18:32
professionalKarthik_Mahalingam21-Mar-17 18:32 
QuestionI am not getting expected output. Pin
Mohan Kudimi2-Aug-16 20:52
MemberMohan Kudimi2-Aug-16 20:52 
AnswerRe: I am not getting expected output. Pin
Yaseer Arafat19-Mar-17 10:28
professionalYaseer Arafat19-Mar-17 10:28 
QuestionJson objects to csv file Pin
Member 116580081-May-15 14:05
MemberMember 116580081-May-15 14:05 
AnswerRe: Json objects to csv file Pin
Yaseer Arafat2-Apr-17 3:28
professionalYaseer Arafat2-Apr-17 3:28 
QuestionDoes this generate column names also? Pin
PhrankBooth29-Apr-15 4:35
MemberPhrankBooth29-Apr-15 4:35 
AnswerRe: Does this generate column names also? Pin
Yaseer Arafat31-Jul-15 7:10
professionalYaseer Arafat31-Jul-15 7:10 
GeneralMy vote of 1 Pin
camilot196-Feb-15 15:11
Membercamilot196-Feb-15 15:11 
GeneralRe: My vote of 1 Pin
Yaseer Arafat9-Apr-15 10:08
professionalYaseer Arafat9-Apr-15 10:08 
QuestionNearly! Pin
Ben Deed5-Aug-14 7:03
MemberBen Deed5-Aug-14 7:03 
AnswerRe: Nearly! Pin
Yaseer Arafat13-Aug-14 15:33
professionalYaseer Arafat13-Aug-14 15:33 
QuestionNice article My vote of 5. But Have an issue Pin
coolRahul_1219-May-14 20:14
MembercoolRahul_1219-May-14 20:14 
AnswerRe: Nice article My vote of 5. But Have an issue Pin
Yaseer Arafat30-Jun-14 15:00
professionalYaseer Arafat30-Jun-14 15:00 
Questionerror for static class Pin
Alfredo Lopez Morales20-Mar-14 14:11
MemberAlfredo Lopez Morales20-Mar-14 14:11 
AnswerRe: error for static class Pin
Yaseer Arafat8-Apr-14 11:20
professionalYaseer Arafat8-Apr-14 11:20 
AnswerRe: error for static class Pin
Yaseer Arafat17-Apr-14 9:55
professionalYaseer Arafat17-Apr-14 9:55 
QuestionWant to save result at a specified location Pin
Sweety K15-Jan-14 19:37
MemberSweety K15-Jan-14 19:37 
AnswerRe: Want to save result at a specified location Pin
Yaseer Arafat17-Apr-14 9:57
professionalYaseer Arafat17-Apr-14 9:57 
Questionupper Pin
Kasper Skov10-Dec-13 3:42
MemberKasper Skov10-Dec-13 3:42 
QuestionNeed to escape commas and double quotation marks Pin
Thiện Mẫn Hoàng26-May-13 0:52
MemberThiện Mẫn Hoàng26-May-13 0:52 
AnswerRe: Need to escape commas and double quotation marks Pin
Yaseer Arafat16-Jan-14 17:46
professionalYaseer Arafat16-Jan-14 17:46 
GeneralMy vote of 5 Pin
Carsten V2.023-Mar-13 21:57
MemberCarsten V2.023-Mar-13 21:57 
GeneralRe: My vote of 5 Pin
Yaseer Arafat26-Mar-13 13:09
professionalYaseer Arafat26-Mar-13 13:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.