Hacker News new | ask | show | jobs
by ucarion 2047 days ago
One thing that's a bit unclear to me about properties, as described in this article, is how they should behave with respect to serialization.

For instance, in C#, both System.Text.Json and Newtonsoft.Json will get and serialize all properties, regardless of whether they are virtual "projections" (like the "red" property in the article's RgbColor example) or "plain" properties. Similarly, all properties are deserialized and set when doing the reverse.

This has the consequence that you may have redundant information in your serialization format. That's not the end of the world, and in fact there are some use-cases for this. The bigger consequence is that you can have redundant and conflicting information in the serialized data you read in.

For instance, adapting the author's example to C#:

https://try.dot.net/?fromGist=1bb01bd2b78a3212c52b40ff7955c0...

You get a different deserialization result depending on the order of the properties in the JSON, because the last property wins and the properties are mutually inconsistent with respect to the underlying data model.

Is the conclusion from this that objects which you intend to serialize should avoid using this "properties" feature, or else be extremely deliberate about what properties to include in the serialization format?

2 comments

This is an interesting question, I was not aware of this behavior in C#. It looks like the solution is to use annotations to specify a property as being ignored.

The intended behavior is to serialize all fields of an object (some properties have backing fields, others don't). You wouldn't serialize properties themselves for the same reason a getter/setter on it's own wouldn't be serialized - only the data stored.

Put simply, I would say C# has the wrong default behavior here.

I don't know about JSON but the XML serialisation code checks for a DefaultValue attribute and if the value is the default it ignores it on serialisation. You can also ignore properties if they don't need serialisation.

Your example looks sloppy but it can get messy as the project evolves. I had some code where I mistakenly removed some XmlAttribute attributes in one release and it was painful to resolve in the next release.

Having said that I will still use it again, just carefully.