-
Notifications
You must be signed in to change notification settings - Fork 4.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
JsonSerializer throws InvalidCastException #31553
Comments
Here is another simpler example. This code throws an exception when IgnoreNullValues=true, and doesn't throw when IgnoreNullValues=false:
|
This should also be fixed in 3.0 (still in Maintenance) and 3.1 (LTS). I reproduced that issue also in 3.1.101 and in 3.1.200-preview-014883. |
After this upgrade https://devblogs.microsoft.com/aspnet/blazor-webassembly-3-2-0-preview-3-release-now-available/ |
I am using 3.1.0 and also having this issue. |
In fact System.Text.Json.JsonSerializer does not support HashSet<> |
Seems like it has been fixed in the master branch for .NET 5 - https://github.com/dotnet/installer/blob/master/README.md#installers-and-binaries: #!/usr/bin/env bash
# linux
mkdir /tmp/dotnet5
curl -sSL https://aka.ms/dotnet/net5/dev/Sdk/dotnet-sdk-linux-x64.tar.gz | tar -xvz -C /tmp/dotnet5 > /dev/null
/tmp/dotnet5/dotnet new console -n testhashset
cat <<'EOF' > testhashset/Program.cs
using System;
using System.Collections.Generic;
using System.Text.Json;
class Program
{
class MyClass
{
public HashSet<int> X { get; set; } = new HashSet<int>();
}
public static void Main()
{
var myObject = JsonSerializer.Deserialize<MyClass>(@"{""X"":[2,1]}",
new JsonSerializerOptions { IgnoreNullValues = true });
Console.WriteLine("Count of {0} is: {1}", nameof(myObject.X), myObject.X.Count);
}
}
EOF
/tmp/dotnet5/dotnet publish testhashset/ -o my-publish-dir/ /p:PublishSingleFile=true -r linux-x64
./my-publish-dir/testhashset
# prints
#> Count of X is: 2 |
Does it mean I won't be able to use it in my Asp.Net Core 3.1 project? That sounds terrible since .net core 5.0 is in preview and some other dependencies may have some issue. |
Until then
|
Thank you @GioviQ for your tip. I eventually make it working by installing
|
Using .NET Core 3.0 or 3.1.100-preview3-014645, an
ICollection<string>
property with a private backing field assigned a custom implementation fails to serialize.Error message
Stack trace
This was discovered while attempting to serialize a
Client
model from IdentityServer4. I've created a bare-bones project duplicating the error. Serialization occurs correctly with Newtonsoft.Json.The text was updated successfully, but these errors were encountered: