views:

86

answers:

1

I have a file named config.json. Here's its contents:

{
    dataSources:
    [
        "http://www.blahblah.com/blah",
        "http://www.blahblah.com/blah2",
        ...
    ],

    skills:
    [
        {
            "name": "foobaris",
            "regex": "pattern"
        },
        ...
    ]
}

I want to create a Config object out of this data as easily and succinctly as possible. Config is defined as:

public class Config
{
    public IEnumerable<Uri> DataSources { get; set; }
    public IEnumerable<KeyValuePair<string, Regex>> Skills { get; set; }
}

What's the easiest route?

Because Config.DataSources is Uris, and .Skills has Regexs, I currently have to derserialize (i.e. RawConfig rawConfig = new JavaScriptSerializer().Deserialize<RawConfig>(configFileContents)) the config file into this struct first:

public struct RawConfig
{
    public IEnumerable<string> DataSources { get; set; }
    public IEnumerable<RawConfigSkill> Skills { get; set; }
}

public struct RawConfigSkill
{
    public string Name { get; set; }
    public string Regex { get; set; }
}

...Then convert that struct into a Config (e.g. new Config(rawConfig)).

Can I void this?

+1  A: 

I see this scenario fairly often.

We have some data that needs to be parsed from a text format, and we have tools that do the parsing for us, and we need the result in some particular object graph of our own.

This happens often it seems with json, with custom application configuration sections, with command line arguments .. just to name a few scenarios.

In these cases, I personally prefer to keep the steps separate. Use the tool/library (in your case, JavaScriptSerializer) to parse the text into an intermediate object. Then map the intermediate object to your final object (in other words, what you're already doing).

Trying to accomplish it in one fell swoop usually makes it more complicated than it needs to be. Encapsulate the two operations under one method call and be done with it.

We just roll with the fact that trying to get the parsing tool to output the exact object graph we want is almost always more trouble than its worth.

And of course lots of things can make that second step simpler - LINQ to objects expressions, AutoMapper, etc.

qstarin