Search code examples
c#jsonrefactoringgeneric-collections

Using a Variable as List Type in C#


I am currently using a list to handle a JSON string which works fine for one instance of this, as can be seen below. What I want to do is make these methods that handle the conversion completely generic so I can use them for multiple JSON strings.

This is a snippet of my current code as it stands.

public class GetPerson
{
    public string fooName { get; set; }
    public string fooAddress { get; set; }
    public string fooPosition { get; set; }
}
public class GetPosition
{
    public string fooTitle { get; set; }
    public string fooDepartment { get; set; }
    public string fooSalary { get; set; }
}

    private static List<GetPerson> ConvertToList(string jsonString)
    {
        List< listJson = new List<JsonObject>();
        listJson = (List<GetPerson>)JsonConvert.DeserializeObject<List<GetPerson>>(jsonString);
        return listJson;
    }

This is just a quick sample but the List<GetPerson> is what I need to be generic so it can be reused, because as it stands the GetPosition will obviously not work with this, as I would want to be able to iterate through my code changing the type accordingly.

Is there a way I can assign a variable as a type? I saw another question about this but it didn't go into detail. Or is there another way that this could be achieved?

Thanks in advance.


Solution

  • You can use Generics to help make the ConvertToList function reusable for different types

    private static List<T> ConvertToList<T>(string jsonString)
    {
        return (List<T>)JsonConverty.DeserializeObject<List<T>>(jsonString();
    }
    

    You can now call it using both GetPerson and GetPosition as the generic type.

    var listOfPeople = ConvertToList<GetPerson>(personJson);
    var listOfPositions = ConvertToList<GetPosition>(positionJson);
    

    You can read more about Generics on MSDN.

    Also, if all that you want to do is to [de]serialize JSON, you might want to consider a third-party library for that like JSON.net, Jil or ServiceStack.Text, all of which have built in functions to do what you are trying to do.