Click here to Skip to main content
15,885,366 members
Articles / Programming Languages / XML
Tip/Trick

Create CSV from JSON in C#

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

Introduction

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:

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

I need it deserialized first:

C#
XmlNode xml = JSON.DeserializeXmlNode("{records:{record:" + json + "}}"); 
C#
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].ToCSV(",");

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

C#
public static string ToCSV(this DataTable table,string delimator)
{
    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" : delimator);
    }
    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" : 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

C#
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.

C#
public string DataTableToJsonObj(DataTable dt)
{
    DataSet ds = new DataSet();
    ds.Merge(dt);
    StringBuilder JsonString = new StringBuilder();
    if (ds != null && ds.Tables[0].Rows.Count > 0)
    {
        JsonString.Append("[");
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            JsonString.Append("{");
            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)
            {
                JsonString.Append("}");
            }
            else
            {
                JsonString.Append("},");
            }
        }
        JsonString.Append("]");
        return JsonString.ToString();
    }
    else
    {
        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

Usage

JSON

C#
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)

JSV

C#
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)

CSV

C#
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)

Reference

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.

License

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


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