Is there any way to deserialize a JSON string of one class into another class? #101790
Replies: 1 comment 6 replies
-
It is unfortunately very unclear what your problem is and what you exactly mean by saying "the deserialization of this JSON fails". Tell exactly what your code does (how it does the deserialization exactly), what the exact expected behavior re (de)serialization is, and the exact actual (de)serialization behavior you observed. Note that deserialization of old config Json data (serialized from your old Config class) into an instance of your new Config class is not failing because of the serializer's default behavior. The serializer simply ignores the EnableFacebook value from the Json data and otherwise happily populates the the |
Beta Was this translation helpful? Give feedback.
-
My program has a class with many properties that store all the settings and information for a user's project, like this:
When the user saves, I serialize this class to JSON and save it to a text file. Conversely, when the user loads a project, I read the text file and deserialize the JSON to restore the project's settings and information.
Now I have a tricky problem: when I update the software, I may add some features and need to modify or add new properties to this class, like this:
When the user updates the software and then loads a project, the deserialization of this JSON fails because the structure of the two classes has changed.
I may use a database later, but now the project schedule is tight and I can't make too big a switch. Maybe there are better ways to save settings in a plain text file? How can I solve this problem?
After running some tests, I figured out the problem. Since I need to use AOT compilation, I have to use source generation in System.Text.Json. The code for this part is shown below:
However, when I modify the class used for saving information, the old user save file does not match any items in the source generation, which causes an error when deserializing the JSON: "JsonTypeInfo? option equals null, which may mean that an unspecified structure cannot be JSON serialized."
This seems to mean that I need to save all versions of the project's save classes in source generation, which is a bit too much.
Beta Was this translation helpful? Give feedback.
All reactions