Back to CSV – Convert CSV text to Objects; via JSON

As Json is easier to read and write then Xml. It follows that CSV (comma seperated values) is easier to read and write then Json. CSV also has tools such as Excel and others that make it easy to work with and create. So if you ever want to create a config or data file for your next app, here is some code to convert CSV to JSON to POCO objects.

Control Method

public void ConvertCsvToObjects()
    string csv = File.ReadAllText(@"c:\temp\mycsv.txt");
    /* mycsv.txt - Note the doube quotes around strings are required by json.
    ID, Name, Price
    1, "ABC", 1200.00
    2, "Zip Co.", 1400
    3, "Contoso", 5000

    // Step 1: Reshape csv to a json array format.
    string json = csv.CsvToJson();
    /* JSON text
    {ID: 1, Name: "ABC", Price: 1200.00},
    {ID: 2, Name: "Zip Co.", Price: 1400},
    {ID: 3, Name: "Contoso", Price: 5000}

    // Step 2: Convert json to objects.
    List<Customer> customers = json.FromJson<List<Customer>>();
    foreach(var cust in customers)
        Console.WriteLine("{0}\t{1}\t{2:c}", cust.ID, cust.Name, cust.Price);
    /* Output.
    1    ABC    $1,200.00
    2    Zip Co.    $1,400.00
    3    Contoso    $5,000.00
public class Customer
    public int ID {get;set;}
    public string Name { get; set; }
    public decimal Price { get; set; }

CsvToJson extention method

/// <summary>
/// Converts a CSV string to a Json array format.
/// </summary>
/// <remarks>First line in CSV must be a header with field name columns.</remarks>
/// <param name="value"></param>
/// <returns></returns>
public static string CsvToJson(this string value)
    // Get lines.
    if (value == null) return null;
    string[] lines = value.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
    if (lines.Length < 2) throw new InvalidDataException("Must have header line.");

    // Get headers.
    string[] headers = lines.First().SplitQuotedLine(new char[] { ',' }, false);

    // Build JSON array.
    StringBuilder sb = new StringBuilder();
    for (int i = 1; i < lines.Length; i++)
        string[] fields = lines[i].SplitQuotedLine(new char[] { ',', ' ' }, true, '"', false);
        if (fields.Length != headers.Length) throw new InvalidDataException("Field count must match header count.");
        var jsonElements = headers.Zip(fields, (header, field) => string.Format("{0}: {1}", header, field)).ToArray();
        string jsonObject = "{" + string.Format("{0}", string.Join(",", jsonElements)) + "}";
        if (i < lines.Length - 1)
            jsonObject += ",";
    return sb.ToString();

FromJson extention method

public static T FromJson<T>(this string json)
    JavaScriptSerializer ser = new JavaScriptSerializer();
    return ser.Deserialize<T>(json);
This entry was posted in Uncategorized. Bookmark the permalink.

3 Responses to Back to CSV – Convert CSV text to Objects; via JSON

  1. Charles says:

    Okay, I have been trying forever to figure this out – where do the SplitQuotedLine and Zip functions you reference here come from?

  2. Unknown says: Dell latitude d820 Battery Dell latitude d830 Battery Acer aspire 5520 Battery Acer aspire 5920 Battery Acer batbl50l6 Battery Dell 6400 Battery Dell d620 Battery Dell d630 Battery Dell d820 Battery Dell d830 Battery Dell e1505 Battery Dell gd761 Battery Dell gk479 Battery Dell inspiron 1520 Battery Dell inspiron 6400 Battery×99.htm Mitac bp-8×99 Battery Sony vgp-bps2 Battery Sony vgp-bps2a Battery Sony vgp-bps2b Battery Sony vgp-bps2c Battery Sony vgp-bps5 Battery Sony vgp-bps5a Battery Hp 530 Battery Hp dv2000 Battery Hp dv2200 Battery Hp dv4000 Battery Hp dv6000 Battery Acer batbl50l6 Battery Hp nc8230 Battery Hp nc8430 Battery Hp nw8000 Battery Hp nw8200 Battery laptop battery laptop batteries Acer 1600 1680 19V 3.42A 65W 5.5MM*1.7MM Adapter Acer 1600 1680 19V 3.42A 65W 5.5MM*2.5MM Adapter Toshiba PA3283U-1ACA 15V 5A 75W 6.3MM*3.0MM Adapter Toshiba PA3467U PA3396U 19V 3.42A 65W 5.5MM*2.5MM Adapter Toshiba PA3589U 19V 4.74A 90W 5.5MM*2.5MM Adapter Asus A2 A3 19V 3.42A 65W 5.5MM*2.5MM Adapter Dell 6400 D620 19.5V 3.34A 65W 7.4MM*5.0MM Adapter

Comments are closed.