Click here to Skip to main content
11,716,938 members (78,034 online)
Click here to Skip to main content

Save a Collection of Objects as XML and/or JSON and/or CSV

, 10 Feb 2014 CPOL 5.9K 191 8
Rate this:
Please Sign up or sign in to vote.
How to save a collection of objects as XML, JSON, or CSV

Expansion on a Theme

This tip is an expanded version of what can be found here, where I showed how to save a single instance of a class (an object) to an XML file.

This tip shows how to save a collection (generic list) of objects to an XML, JSON, or CSV file.

All are easy; the only "special" thing you have to do to get the JSONification of the object collection to be written out is to add a reference to Json.NET to your project (IOW, NuGet Newtonsoft's JSON.NET from within Visual Studio).

I am attaching the source, but in a nutshell, it defines a class, populates a generic list of that class with a few instances of the class, and then writes that list out as XML and/or JSON and/or CSV. Again, there's not much to it, as you can see in the code snippets below.

Define a generic list and a class:

private List<BilingualBook> classicsBilingual;
public class BilingualBook
{
    public string Author { get; set; }
    public string SourceLang { get; set; }
    public string TargetLang { get; set; }
    public string EnglishTitle { get; set; }
    public string PaperbackURI { get; set; }
    public string KindleURI { get; set; }
    public string ImageURI { get; set; }
}

Populate, or hydrate/inflate the generic list with instantiations of the class:

private void Popul8Classics()
{
    classicsBilingual = new List<BilingualBook>();
    var AtWi80Daze = new BilingualBook
    {
        Author = "Jules Verne",
        SourceLang = "French",
        TargetLang = "English",
        EnglishTitle = "Around the World in 80 Days",
        PaperbackURI = GetProductURI("1495308081"),
        KindleURI = GetProductURI("B00I0DOYRE"),
        ImageURI = GetImageURI("51BCZUX2-dL")
    };
    classicsBilingual.Add(AtWi80Daze);

    var gulliver = new BilingualBook
    {
        Author = "Jonathan Swift",
        SourceLang = "English",
        TargetLang = "French",
        EnglishTitle = "Gulliver's Travels",
        PaperbackURI = GetProductURI("1495374688"),
        KindleURI = GetProductURI("B00I5319ZO"),
        ImageURI = GetImageURI("517O76OyaWL")
    };
    classicsBilingual.Add(gulliver);
. . .

Save the generic list as XML:

private void SaveAsXML(List<BilingualBook> classics)
{
    const string xmlFilename = "FitTClassics.xml";
    var writer = new System.Xml.Serialization.XmlSerializer(typeof(
        List<BilingualBook>);

    var file = new StreamWriter(xmlFilename);
    writer.Serialize(file, classics);
    file.Close();
}

And/or save the generic list as JSON:

private void SaveAsJSON(List<BilingualBook> classics)
{
    const string jsonFilename = "FitTClassics.json";
    string jsonRepresentation = JsonConvert.SerializeObject(classics);
    File.WriteAllText(jsonFilename, jsonRepresentation);
}

And/or save the generic list as CSV:

private void SaveAsCSV(List<BilingualBook> classicsBilingual)
{
    const string csvFilename = "FitTClassics.csv";
    var csvFile = new List<string>();
    foreach (BilingualBook classic in classicsBilingual)
    {
        csvFile.Add(string.Format("{0},{1},{2},{3},{4},{5},{6}",
            classic.Author, classic.SourceLang, classic.TargetLang,
            classic.EnglishTitle, classic.PaperbackURI, classic.KindleURI,
            classic.ImageURI));
    }
    File.WriteAllLines(csvFilename, csvFile);
}

Now Do Your Part

If you like this tip, stand up in your cubicle, beat your chest like a "Bam-boon", and bellow out menacingly, "The hemlock shakes in the rafter, the oak in the driving keel!" If you really like this tip (or are too chicken to do that), you can instead purchase a book from one of the PaperbackURI or KindleURI links (download the code and run it, or download the XML file).

License

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

Share

About the Author

B. Clay Shannon
Founder "Across Time & Space"
United States United States
Ideaman and Coder at Across Time & Space, creator of "Mark Twain Central" at http://twaincentral.azurewebsites.net/

Peripatetic and picaresque, I have lived in eight states; specifically, besides my native California (where I was born and where I now again reside) in chronological order: New York, Montana, Alaska, Oklahoma, Wisconsin, Idaho, and Missouri.

I am also a writer of both fiction (for which I use a nom de plume, "Blackbird Crow Raven", as a nod to my Native American heritage - I am "½ Cowboy, ½ Indian") and nonfiction: http://www.lulu.com/spotlight/blackbirdcraven

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150901.1 | Last Updated 10 Feb 2014
Article Copyright 2014 by B. Clay Shannon
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid