Skip to content
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

System.Text.Json.JsonSerializer can't deserialize readonly collection property #31015

Closed
chenyj796 opened this issue Sep 29, 2019 · 1 comment

Comments

@chenyj796
Copy link

I have a Config class which contains a readonly property named Items.
I serialize it to json string, and then deserialize the json string back as below.
After run the Run() method, cfg2.Items is empty when cfg3.Items contains one item.

public class Config
{
    public HashSet<string> Items { get; } = new HashSet<string>();
}

public class ConfigTest
{
    public void Run()
    {
        var cfg = new Config();
        cfg.Items.Add("item1");
        var json = System.Text.Json.JsonSerializer.Serialize(cfg);
        var cfg2 = System.Text.Json.JsonSerializer.Deserialize<Config>(json);
        var cfg3 = Newtonsoft.Json.JsonConvert.DeserializeObject<Config>(json);
    }
}
@steveharter
Copy link
Member

This is by design for collections that don't have a setter. To avoid issues with adding to pre-populated collections (that the serializer doesn't instantiate) the deserializer uses "replace" semantics which requires the collection to have a setter.

However if there is no setter (as in your case) https://github.com/dotnet/corefx/issues/39477 is tracking that feature.

@msftgits msftgits transferred this issue from dotnet/corefx Feb 1, 2020
@msftgits msftgits added this to the 5.0 milestone Feb 1, 2020
@ghost ghost locked as resolved and limited conversation to collaborators Dec 12, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants