3
I have a method I use to deserialize data:
public static class CustomJson<T> where T: class, new()
{
public static T Deserialize(string data)
{
try
{
return string.IsNullOrEmpty(data)
? default(T)
: Newtonsoft.Json.JsonConvert.DeserializeObject<T>(data);
}
catch (Exception ex)
{
throw new Exceptions.SerializationException(SerializationType.Json, ex);
}
}
}
The type to be used in deserialization I know only in Runtime:
public void TesteCustomJson(string package, string methodName)
{
try
{
var serviceFactory = new ServiceFactory();
var service = serviceFactory.GetService<ITesteService>();
var method = service.GetType().GetMethod(methodName);
if (method != null)
{
var parameter = method.GetParameters().FirstOrDefault();
if (parameter != null)
{
var parameterType = parameter.ParameterType;
var result = Framework.Utils.Serialization.CustomJson<parameterType>.Deserialize(package);
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
Doing so does not compile, the following error is generated:
The type or namespace name 'parameterType' could not be found (are you Missing a using Directive or an Assembly Reference?)
Is there any way to pass the kind to be deserialized knowing it only at runtime?
Why do you only know in Runtime? Are you sure of this? From the section posted this is not clear. Beyond this. Do you really want a memory error or other error reported as a serialization error? http://answall.com/a/30168/101
– Maniero
I actually know the types, but how can I treat them in a generic way when there are hundreds of different types? I think that if we take the type in Runtime could be less laborious. As for the error treatment, we will improve it, here was just an example.
– Paulo Balbino
If you know the type at compile time, you should deal with it at compile time. The path was correct. Maybe the problem is in the use but you have not posted relevant information of how you are using. Since I haven’t seen all the code you can’t say but I think you know what kind of
parameter
, then use this guy and be happy.– Maniero
I posted the complete test method.
– Paulo Balbino
http://stackoverflow.com/a/232621/4322614
– mateusalxd
Thanks @Matthew, corresponds with the reply of Omni.
– Paulo Balbino
Yes @Paulobalbino, I found this solution in the OS, but when I went to see had already answered, not to miss the trip posted what I found.
– mateusalxd