mercredi 15 avril 2020

How do I get the generic, T, of a List

I am writing a JsonMapper in order to map a JSON String to the fields of a C# class using SimpleJSON, similar to JSONUtility so that I can have greater control over the mapping. I'm not inclined to write the code for mapping each class as I will have many multiple classes with varying fields.

public class JsonMapper<T>
{
    public string jsonString;
    public T mappedObj;

    public JsonMapper(string json)
    {
        jsonString = json;
        JSONNode jn = JSON.Parse(json);

        Type t = Assembly.GetExecutingAssembly().GetType(typeof(T).FullName);
        mappedObj = (T) Activator.CreateInstance(t);

        foreach (FieldInfo field in typeof(T).GetFields())
        {
            switch (field.FieldType.Name)
            {
                case "Int32":
                    field.SetValue(mappedObj, int.Parse(jn[field.Name]));
                    Debug.Log(field + ": " + field.GetValue(mappedObj));
                    break;
                    ...

I've used reflection in order to map primitive data types so far, but currently I am stuck trying to map lists. I'm trying to obtain the generic, T, of the List, and recursively create another instance of my JsonMapper. Below is an example of what I am trying to achieve:

case "List`1":
    Type genericType = field.FieldType.GetGenericArguments()[0];
    foreach (var genericJson in jn[field.Name])
    {
        //This line does not work, it is pseudocode
        JsonMapper<genericType> recurJM = new JsonMapper<genericType>(genericJson.ToString());
    }
    break;

To do so I have referenced this to invoke generic methods using reflection and this to invoke constructors. However, I can't seem to find a way to invoke a constructor with generics.

My question is: How do I achieve this particular line of code in the above code snippet?

JsonMapper<genericType> recurJM = new JsonMapper<genericType>(genericJson.ToString());




Aucun commentaire:

Enregistrer un commentaire