开发者

Associating a variable with a class in C# (for JSON)

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 开发者_C百科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));
    }


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));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜