Search code examples
c#jsongenericsdatacontract

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

Solution

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