I'm trying to implement a TypeConverter for a custom Node
class of mine. (I was led to this approach by the answer to this question.) In my class NodeConverter : TypeConverter
, I have the following:
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string)
{
// parse the string, return a new node
}
return base.ConvertFrom(context, culture, value);
}
I've also added [TypeConverter(typeof(NodeConverter))]
as an attribute to my Node class. Then in a unit test I have the following:
var str = "{\"Username\":\"123\",\"Name\":\"Test Name\",\"Degree\":0}";
var deserialized = JsonConvert.DeserializeObject<Node>(str);
When I run the unit test, I get this error:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'd3js.Shared.Graph.Node' because the type requires a JSON string value to deserialize correctly.
It's not clear to me what a "JSON string value" is, or how it differs from what I'm using here, so I'm unsure how to proceed.