I have the following class defined:
<TypeConverter(GetType(ExpandableObjectConverter))>
<DataContract()>
Public Class Vector3
<DataMember()> Public Property X As Double
<DataMember()> Public Property Y As Double
<DataMember()> Public Property Z As Double
Public Overrides Function ToString() As String
Return String.Format("({0}, {1}, {2})",
Format(X, "0.00"),
Format(Y, "0.00"),
Format(Z, "0.00"))
End Function
End Class
Using the DataContractJsonSerializer
I receive the following JSON as expected:
{
"Vector": {
"X": 1.23,
"Y": 4.56,
"Z": 7.89
}
}
However, JSON.NET produces:
{
"Vector": "(1.23, 4.56, 7.89)"
}
If I remove the ExpandableObjectConverter
attribute from the class, JSON.NET produces results as expected (same as DataContractJsonSerializer).
Unfortunately I need the ExpandableObjectConverter
so that the class works with a property grid.
Is there any way to tell JSON.NET to ignore ExpandableObjectConverters
?
I prefer to use JSON.NET instead of DataContractJsonSerializer
because it is much easier to serialize enums to their string representations.
Thanks to JRS for posting this. Users of C# can use this translation from VB:
public class SerializableExpandableObjectConverter : ExpandableObjectConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if(destinationType == typeof(string))
{
return false;
}
else
{
return base.CanConvertTo(context, destinationType);
}
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if(sourceType == typeof(string))
{
return false;
}
else
{
return base.CanConvertFrom(context, sourceType);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With