I am switching over my object serialization in my app because it said it was depreciated (https://docs.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide). I am now attempting to use System.Text.Json API's as described in the article as a replacement. Everything works great when I serialize my objects:
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
The issue arises in one of my properties where I am using a dynamic object type. When I try to deserialize it I get this error: "System.InvalidCastException: Conversion from type JsonElement to type String is not valid."
Private Property Answer as Object
I get this I am assuming because the properties type is not strictly defined so when it tries to deserialize it again it doesn't know it's type. The issue is I can't strictly define this type because it could contain data that's either string, boolean, etc.
How do I handle something like this? Not really sure what to do as I am fairly new to JSON.
Thanks