Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems using JSON.NET with ExpandableObjectConverter

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.

like image 831
JRS Avatar asked Jul 09 '13 23:07

JRS


1 Answers

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);
        }
    }
}
like image 108
Victor Chelaru Avatar answered Sep 28 '22 07:09

Victor Chelaru