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

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
10 Feb 2014CPOL1 min read 18.5K   365   9   1
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:

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

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

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

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

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


Written By
Founder Across Time & Space
United States United States
I am in the process of morphing from a software developer into a portrayer of Mark Twain. My monologue (or one-man play, entitled "The Adventures of Mark Twain: As Told By Himself" and set in 1896) features Twain giving an overview of his life up till then. The performance includes the relating of interesting experiences and humorous anecdotes from Twain's boyhood and youth, his time as a riverboat pilot, his wild and woolly adventures in the Territory of Nevada and California, and experiences as a writer and world traveler, including recollections of meetings with many of the famous and powerful of the 19th century - royalty, business magnates, fellow authors, as well as intimate glimpses into his home life (his parents, siblings, wife, and children).

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, including a two-volume social and cultural history of the U.S. which covers important events from 1620-2006: http://www.lulu.com/spotlight/blackbirdcraven

Comments and Discussions

 
QuestionMessage Closed Pin
17-Sep-21 6:43
Member 1536186217-Sep-21 6:43 
PraiseLike Pin
Ali RZB5-Sep-17 2:39
Ali RZB5-Sep-17 2:39 

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.