使用json序列化和反序列化 "object" 类型的属性。收到无效的转换异常。

11 浏览
0 Comments

使用json序列化和反序列化 "object" 类型的属性。收到无效的转换异常。

由于它被弃用,我正在切换我的应用程序中的对象序列化(参见https://docs.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide)。我现在尝试使用文章中描述的 System.Text.Json API 作为替代方案。当我序列化我的对象时一切都很顺利:

 
Function Serialize(ByVal objData As Object) As Byte()
    If objData Is Nothing Then Return Nothing
    Return Encoding.UTF8.GetBytes(JsonSerializer.Serialize(objData, GetJsonSerializerOptions()))
End Function
Function Deserialize(Of T)(ByVal byteArray As Byte()) As T
    If byteArray Is Nothing OrElse Not byteArray.Any() Then Return Nothing
    Return JsonSerializer.Deserialize(Of T)(byteArray, GetJsonSerializerOptions())
End Function
Private Function GetJsonSerializerOptions() As JsonSerializerOptions
    Return New JsonSerializerOptions() With {
        .PropertyNamingPolicy = Nothing,
        .WriteIndented = True,
        .AllowTrailingCommas = True,
        .DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
    }
End Function

问题出现在一个使用动态对象类型的属性上。当我尝试对其进行反序列化时,我收到以下错误提示:"System.InvalidCastException: 无法将类型 JsonElement 转换为类型 String。"

 
Private Property Answer as Object

我认为这是因为属性的类型没有严格定义,所以当它尝试再次进行反序列化时,它不知道它的类型。问题是我无法严格定义此类型,因为它可能包含字符串、布尔值等数据。

我应该如何处理这样的情况?由于我对JSON还不太熟悉,所以不太确定该怎么办。

谢谢。

0