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.

Answer

Although I appreciate Rivers’ answer I am really looking for a solution that ignores all expandable object converters automatically (like the DataContractJsonSerializer does) rather than building a custom JsonConverter for each offending class.

I have found the following two solutions:

  1. Use the built in DataContractJsonSerializer instead (at the expense of some other conveniences of JSON.NET).
  2. Use a custom ExpandableObjectConverter (see below).

Since the default ExpandableObjectConverter supports converting to/from string, JSON.NET is serializing the class with a string. To counteract this I have created my own expandable object converter which does not allow conversions to/from string.

Imports System.ComponentModel

Public Class SerializableExpandableObjectConverter
   Inherits ExpandableObjectConverter

   Public Overrides Function CanConvertTo(context As System.ComponentModel.ITypeDescriptorContext, destinationType As System.Type) As Boolean

      If destinationType Is GetType(String) Then
         Return False
      Else
         Return MyBase.CanConvertTo(context, destinationType)
      End If

   End Function

   Public Overrides Function CanConvertFrom(context As System.ComponentModel.ITypeDescriptorContext, sourceType As System.Type) As Boolean

      If sourceType Is GetType(String) Then
         Return False
      Else
         Return MyBase.CanConvertFrom(context, sourceType)
      End If

   End Function

End Class

Applying the above converter works flawlessly with JSON.NET and with the property grid control!

Attribution
Source : Link , Question Author : JRS , Answer Author : JRS

Leave a Comment