JRS*_*JRS 5 c# vb.net json typeconverter json.net
我定义了以下类:
<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
Run Code Online (Sandbox Code Playgroud)
使用DataContractJsonSerializer我按预期收到以下JSON:
{
"Vector": {
"X": 1.23,
"Y": 4.56,
"Z": 7.89
}
}
Run Code Online (Sandbox Code Playgroud)
但是,JSON.NET产生:
{
"Vector": "(1.23, 4.56, 7.89)"
}
Run Code Online (Sandbox Code Playgroud)
如果我ExpandableObjectConverter从类中删除该属性,JSON.NET会按预期生成结果(与DataContractJsonSerializer相同).
不幸的是,我需要ExpandableObjectConverter这样,以便该类使用属性网格.
有没有办法告诉JSON.NET忽略ExpandableObjectConverters?
我更喜欢使用JSON.NET,而不是DataContractJsonSerializer因为将枚举序列化为字符串表示更容易.
虽然我很欣赏Rivers的回答,但我真的在寻找一种自动忽略所有可扩展对象转换器的解决方案(比如DataContractJsonSerializer),而不是为每个违规类构建一个自定义JsonConverter.
我找到了以下两种解决方案:
由于默认的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
Run Code Online (Sandbox Code Playgroud)
应用上面的转换器与JSON.NET和属性网格控件完美配合!