I have a c# class that allows you to specify a generic type. I would like to be able to reuse this class to remove the noise of a json wrapper that all objects will share, a value
property that holds the data I need.
If the reusable class has a property of value
that gets me the first step of the way. But I'm having trouble deserializing into the generic type supplied, because when I cast it always returns null
. I know this is because the actual type of value
after deserialization is probably JObject
or similiar, I forget the type exactly. You can see in my demo app that it does indeed grab all of the data, but I can't just cast it into my generic type, because it isn't actually that type yet.
var get1 = JsonConvert.DeserializeObject<BaseResponse<NameObj>>("{ value: {...} }");
var name1 = get1.Get();//name1 is null
var getList1 = JsonConvert.DeserializeObject<BaseResponse<NameObj>>("{ value: [{...}] }");
var nameList = getList1.List();//nameList is null
public class BaseResponse<T> where T : BaseObj
{
public object value;
public T Get()
{
return value as T;
}
public List<T> List()
{
return value as List<T>;
}
}
public class NameObj : BaseObj
{
public string Name { get; set; }
}
I'll have more than one type of BaseObj class.
So, I'm wondering what is better:
- manipulate json first to grab
value
out, and deserialize that - fix how I'm deserializing the
BaseReponse<T>
to better get at the generic inside thevalue
property
I suppose solution 1 will do for now, since all of the json follows that pattern, but I was hoping for a pure deserialize instead of having to do string manipulation.
repo here: https://github.com/nateous/JSONDeserializeBaseWithGeneric