I'm using LitJson and BestHTTP libraries on a Unity3D project and I would write my custom ResponseSerializer object. The goal is create a method that uses generics to map the possible response into my wanted object.
So, my first attempt was something similar:
public static void SerializeResponse<T>(string error, HTTPResponse response, string insideKey, Action<APIResource<T>> callback)
where T:new()
{
var apiResource = new APIResource<T>();
if (error != null)
{
apiResource.error = error;
}
else
{
apiResource.error = null;
JsonData jsonData = JsonMapper.ToObject(response.DataAsText);
apiResource.resource = (T)(jsonData[insideKey]);
}
callback(apiResource);
}
But in this way I get compiling error on the
apiResource.resource = (T)(jsonData[insideKey]);
with message:
Cannot convert type
LitJson.JsonData
toT
The possible types of needed T are only 4 (at the moment):
- string
- int
- float
- bool
So, I started playing with switch on type but everytime I get compiling error. My last attempt was this (taken from https://stackoverflow.com/a/4478535/2838073) :
public static void SerializeResponse<T>(string error, HTTPResponse response, string insideKey, Action<APIResource<T>> callback)
where T:new()
{
var apiResource = new APIResource<T>();
if (error != null)
{
apiResource.error = error;
}
else
{
apiResource.error = null;
JsonData jsonData = JsonMapper.ToObject(response.DataAsText);
var @switch = new Dictionary<Type, Action> {
{ typeof(string), () => { apiResource.resource = (string)jsonData[insideKey]; } },
{ typeof(int), () => { apiResource.resource = (int)jsonData[insideKey]; } },
{ typeof(float), () => { apiResource.resource = (float)jsonData[insideKey]; } },
{ typeof(bool), () => { apiResource.resource = (bool)jsonData[insideKey]; }}
};
@switch[typeof(T)]();
}
callback(apiResource);
}
But the error is always the same:
Cannot implicitly convert type
mytype
toT
What am I doing wrong? I'm not pratical on C# with generics pattern and I would to learn from my mistakes.