I have simple DTO
public class SimpleDto
{
public int Status { get; set; }
public long FromDate { get; set; }
public long ToDate { get; set; }
}
And I have ProxyDto with TypeConverterAttribute
:
[TypeConverter(typeof(SimpleConvert<SimpleDto>))]
public class ProxyDto<T>
{
public T Object { get; set; }
}
Here is the implementation of SimpleConvert
:
public class SimpleConvert<T> : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string) ||
base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
var strValue = value as string;
return strValue != null
? new ProxyDto<T>{ Object = JsonConvert.DeserializeObject<T>(strValue)}
: base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
var val = value as ProxyDto<T>;
return destinationType == typeof(string) && val != null ? val.Object.ToJson() : base.ConvertTo(context, culture, value, destinationType);
}
}
Also I have simple Json for DTO:
{"Status":3,"FromDate":12345,"ToDate":54321}
When I try to deserialize this object via proxy
var obj = JsonConvert.DeserializeObject<ProxyDto<SimpleDto>>(str);
it fails with Exception 'Newtonsoft.Json.JsonSerializationException'
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'Detect_Console_Application_Exit2.ProxyDto`1[Detect_Console_Application_Exit2.SimpleDto]' because the type requires a JSON string value to deserialize correctly. To fix this error either change the JSON to a JSON string value or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'Status', line 1, position 10.
But if my Json has escaping Json:
"{\"Status\":3,\"FromDate\":12345,\"ToDate\":54321}"
it works well. I don't understand why the first JSON object is not correct. Can you help me?
Update
Here is ToJson
method:
public static class Extension
{
public static string ToJson(this object val)
{
return JsonConvert.SerializeObject(val);
}
}