c# - 将 JSON.NET 与 ExpandableObjectConverter 结合使用时出现问题

标签 c# json vb.net json.net typeconverter

我定义了以下类:

<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

使用 DataContractJsonSerializer 我按预期收到以下 JSON:

{
  "Vector": {
    "X": 1.23,
    "Y": 4.56,
    "Z": 7.89
  }
}

然而,JSON.NET 产生:

{
  "Vector": "(1.23, 4.56, 7.89)"
}

如果我从类中删除 ExpandableObjectConverter 属性,JSON.NET 会产生预期的结果(与 DataContractJsonSerializer 相同)。

不幸的是,我需要 ExpandableObjectConverter 以便该类使用属性网格。

有没有办法告诉 JSON.NET 忽略 ExpandableObjectConverters

我更喜欢使用 JSON.NET 而不是 DataContractJsonSerializer,因为将枚举序列化为它们的字符串表示形式要容易得多。

最佳答案

尽管我很欣赏 Rivers 的回答,但我确实在寻找一种解决方案,它可以自动忽略所有可扩展对象转换器(就像 DataContractJsonSerializer 所做的那样),而不是为每个有问题的类构建自定义 JsonConverter。

我找到了以下两种解决方案:

  1. 改为使用内置的 DataContractJsonSerializer(以牺牲 JSON.NET 的一些其他便利性为代价)。
  2. 使用自定义 ExpandableObjectConverter(见下文)。

由于默认的 ExpandableObjectConverter 支持转换为字符串/从字符串转换,因此 JSON.NET 正在使用字符串序列化该类。为了解决这个问题,我创建了自己的可扩展对象转换器,它不允许与字符串之间的转换。

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

应用上述转换器可以完美地处理 JSON.NET 和属性网格控件!

关于c# - 将 JSON.NET 与 ExpandableObjectConverter 结合使用时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17560085/

相关文章:

.net - 在 .Net 中动态构建文件路径

vb.net - 如何获取网页上显示的所有图像的 URL 列表?

c# - 当 Ping 往返时间超过 50 毫秒时,如何更改 PictureBox 的图像?

c# - 如何有效地左填充字节数组

c# - 让wcf客户端等待回调

javascript - 检索与 angularjs 中的 id 关联的行

javascript - 如何使用jquery动态添加按钮

c# - Windows 窗体 : change dataGridView's first cell origin?

python - 在 MySQL 中存储 JSON?

vb.net - 是否可以向后执行 For...Each 循环?