views:

36

answers:

1

I'm having to grab API-provided JSON for a project of mine, and that means deserialising JSON using a class, and I've chosen to go with DataContract classes. In any case, different URLs correspond to different JSON outputs for the API.

So what am I asking? It's to see if there's any better way to have URLs corresponding to the DataContract classes than having to create public T GetObject<T>(string uri) and using it with GetObject<ExampleDataContract>("http://blah/").

The below code shows my current attempt, which I'm thinking isn't a very good idea at all, not to mention the fact that if I ever change the namespace, I'm in for some fun.

    public T GetObject<T>()
    {
        string uri = "";
        string type = typeof(T).ToString();
        switch (type)
        {
            case "Namespace.ExampleDataContract":
                uri = "http://www.example.com/blah.json";
                break;
        }

        return JsonHelper.Deserialize<T>(this.GetJson(uri));
    }
+1  A: 

There's one problem I see with your approach: What if you have two different URLs, both returning an ExampleDataContract? Using your method, you would only be able to fetch one of them, since the type uniquely determines the URL.

In any case, you are right that getting rid of the magic string "Namespace.ExampleDataContract" is a good idea. Using if is one option, more are shown in SO questions 708911 and 298976.

public T GetObject<T>()
{
    string uri = "";
    if (typeof(T) == typeof(Namespace.ExampleDataContract))
    {
        uri = "http://www.example.com/blah.json";
    }
    else if (typeof(T) == ...)
    {
        ...
    }
    else
    {
        ... // throw some exception
    }

    return JsonHelper.Deserialize<T>(this.GetJson(uri));
}
Heinzi
I'm asking if there's any better method than a giant if sequence/etc, so I assume it is your opinion that this is the best method that can be used?
a2h
@a2h: Well, if you want your URLs to be determined by the type, you will need a list Type1 -> Url1, Type2 -> Url2, ... *somewhere*. Whether you put it in a giant `if` sequence, in a static `Dictionary<Type, String>` or in some configuration file is basically a question of taste and of your exact requirements.
Heinzi