DudeWhoWantsToLearn
DudeWhoWantsToLearn

Reputation: 771

How can I deserialize a Yaml object containing strings into a List<string>?

I created a Yaml with filenames, so I can make my program check if every file of the list exists. I haven"t done much with yaml yet, and the documentations don't really help me.

This is my Yaml (It's pretty small):

DLLs:
    - Filename1
    - Filename2
    - Filename3

At the moment, this is my code:

using (var reader = new StringReader(File.ReadAllText("./Libraries/DLLList.yml")))
{
    /*
     * List<string> allDllsList = deserialized yaml.getting all values of the "DLLs"-list
     */

    var deserializer = new Deserializer();

    var dlls = deserializer.Deserialize<dynamic>(reader)["DLLs"] as List<Object>;
    /*This gives me the Error "Object System.Collections.Generic.Dictionary`2[System.Object,System.Object] cannot be converted into "System.String""*/
    List<string> allDllsList = dlls.Cast<String>().ToList();
}

Can someone explain to me how I can get the values out of the Yaml file, and why it works in the way you do it?

Edit: Now it works, I used the wrong yaml, I had 2 versions

Upvotes: 0

Views: 1907

Answers (1)

First, take the return value from deserializer.Deserialize<dynamic>(reader) and inspect it in the debugger. It's a Dictionary<String, Object>, and it's got an entry named "DLLs" that contains a List<Object>. The objects in that list are all strings. There you go:

var dlls = deserializer.Deserialize<dynamic>(reader)["DLLs"] as List<Object>;

//  Use .Cast<String>() as shown if you want to throw an exception when there's something 
//  that does not belong there. If you're serious about validation though, that's a bit 
//  rough and ready. 
//  Use .OfType<String>() instead if you want to be permissive about additional stuff 
//  under that key.
List<string> allDllsList = dlls.Cast<String>().ToList();

Upvotes: 1

Related Questions