Patrik Valkovič
Patrik Valkovič

Reputation: 724

Packed object into fundamental type in generic method

I am using Newtonsoft.JSON library to serialize and deserialize object in generic method. The problem is that fundamental types are parsed differently.

public T? GetKey<T>(string key) where T : struct
{
    string content = CrossSettings.Current.GetValueOrDefault(key, null);
    if (content == null)
        return null;
    object o = Newtonsoft.Json.JsonConvert.DeserializeObject(content);
    T v = (T)o;
    return v;
}

When the stored value is "1" (the content variable), the object's inner type is long and I can't cast directly from object to T=int (InvalidCastException). The propper approach will be cast the object first to long and then to the int, but because it is generic method, I don't know what the result type will be.
I tried also using Activator.CreateInstance(o.GetType(), o); but this returns object once again. Do you have any ideas how to solve this problem?

EDIT: simplified problem

string content = "1";
object o = Newtonsoft.Json.JsonConvert.DeserializeObject(content);
int v = /* ??? */;
Debug.Assert(v == 1);

Upvotes: 0

Views: 32

Answers (1)

Igor
Igor

Reputation: 62238

You need to supply a type. The deserializer can't guess what type it should choose from when deserializing. Pass the passed in generic type parameter through to the DeserializeObject method.

public T? GetKey<T>(string key) where T : struct
{
    string content = CrossSettings.Current.GetValueOrDefault(key, null);
    if (content == null)
        return null;
    return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(content);
}

Upvotes: 2

Related Questions