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();
    Console.WriteLine(json);
    /* 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();
    sb.AppendLine("[");
    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 += ",";
        sb.AppendLine(jsonObject);
    }
    sb.AppendLine("]");
    return sb.ToString();
}

FromJson extention method

public static T FromJson<T>(this string json)
{
    JavaScriptSerializer ser = new JavaScriptSerializer();
    return ser.Deserialize<T>(json);
}
About these ads
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:

    http://www.batteryfast.com/dell/latitude-d820.htm Dell latitude d820 Battery http://www.batteryfast.com/dell/latitude-d830.htm Dell latitude d830 Battery http://www.batteryfast.com/acer/aspire-5520.htm Acer aspire 5520 Battery http://www.batteryfast.com/acer/aspire-5920.htm Acer aspire 5920 Battery http://www.batteryfast.com/acer/batbl50l6.htm Acer batbl50l6 Battery http://www.batteryfast.com/dell/6400.htm Dell 6400 Battery http://www.batteryfast.com/dell/d620.htm Dell d620 Battery http://www.batteryfast.com/dell/d630.htm Dell d630 Battery http://www.batteryfast.com/dell/d820.htm Dell d820 Battery http://www.batteryfast.com/dell/d830.htm Dell d830 Battery http://www.batteryfast.com/dell/e1505.htm Dell e1505 Battery http://www.batteryfast.com/dell/gd761.htm Dell gd761 Battery http://www.batteryfast.com/dell/gk479.htm Dell gk479 Battery http://www.batteryfast.com/dell/inspiron-1520.htm Dell inspiron 1520 Battery http://www.batteryfast.com/dell/inspiron-6400.htm Dell inspiron 6400 Battery http://www.batteryfast.com/mitac/bp-8×99.htm Mitac bp-8×99 Battery http://www.batteryfast.com/sony/vgp-bps2.htm Sony vgp-bps2 Battery http://www.batteryfast.com/sony/vgp-bps2a.htm Sony vgp-bps2a Battery http://www.batteryfast.com/sony/vgp-bps2b.htm Sony vgp-bps2b Battery http://www.batteryfast.com/sony/vgp-bps2c.htm Sony vgp-bps2c Battery http://www.batteryfast.com/sony/vgp-bps5.htm Sony vgp-bps5 Battery http://www.batteryfast.com/sony/vgp-bps5a.htm Sony vgp-bps5a Battery http://www.batteryfast.com/hp/530.htm Hp 530 Battery http://www.batteryfast.com/hp/dv2000.htm Hp dv2000 Battery http://www.batteryfast.com/hp/dv2200.htm Hp dv2200 Battery http://www.batteryfast.com/hp/dv4000.htm Hp dv4000 Battery http://www.batteryfast.com/hp/dv6000.htm Hp dv6000 Battery http://www.batteryfast.com/acer/batbl50l6.htm Acer batbl50l6 Battery http://www.batteryfast.com/hp/nc8230.htm Hp nc8230 Battery http://www.batteryfast.com/hp/nc8430.htm Hp nc8430 Battery http://www.batteryfast.com/hp/nw8000.htm Hp nw8000 Battery http://www.batteryfast.com/hp/nw8200.htm Hp nw8200 Battery http://www.batteryfast.com laptop battery http://www.batteryfast.com laptop batteries http://www.batteryfast.com/laptop-ac-adapter/acer/acer-19V-3.42A-65w-5.5mm-1.5mm-small-head.php Acer 1600 1680 19V 3.42A 65W 5.5MM*1.7MM Adapter http://www.batteryfast.com/laptop-ac-adapter/acer/acer-19V-3.42A-65w-5.5mm-2.5mm-big-head.php Acer 1600 1680 19V 3.42A 65W 5.5MM*2.5MM Adapter http://www.batteryfast.com/laptop-ac-adapter/toshiba/toshiba-15V-5A-75w-6.3mm-3.0mm.php Toshiba PA3283U-1ACA 15V 5A 75W 6.3MM*3.0MM Adapter http://www.batteryfast.com/laptop-ac-adapter/toshiba/toshiba-19V-3.42A-65w-5.5mm-2.5mm.php Toshiba PA3467U PA3396U 19V 3.42A 65W 5.5MM*2.5MM Adapter http://www.batteryfast.com/laptop-ac-adapter/toshiba/toshiba-19V-4.74A-90w-5.5mm-2.5mm.php Toshiba PA3589U 19V 4.74A 90W 5.5MM*2.5MM Adapter http://www.batteryfast.com/laptop-ac-adapter/asus/asus-19v-3.42A-65w-5.5mm-2.5mm.php Asus A2 A3 19V 3.42A 65W 5.5MM*2.5MM Adapter http://www.batteryfast.com/laptop-ac-adapter/dell/dell-19.5V-3.34A-65w-7.4mm-5.0mm-with-pin-pa-12.php Dell 6400 D620 19.5V 3.34A 65W 7.4MM*5.0MM Adapter

Comments are closed.