问题
I am trying to store my relational object in a JSON file rather than a SqlLite database as I think it suits better for what I am trying to do. I am using Microsoft's System.Text.Json.Serialization
but that does not seem to be working.
My object is saved to a JSON text file with this:
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
options.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)); // Enums as strings instead of numbers
string jsonString = JsonSerializer.Serialize(doclist, options);
using (StreamWriter sw = new StreamWriter(target, false, System.Text.Encoding.UTF8))
{
sw.Write(jsonString);
sw.Flush();
}
My object contains a couple of DateTime public properties (yes, with get/set) a couple of public string properties and four public HashSet properties. In my trial run, only one of the HashSets is populated, the other three are set to an empty HashSet.
The serialization mostly works, by that I mean that the object is serialized to a JSON text file. The generated JSON file validates correctly as well. However, I observed that while my populated HashSet is properly serialized, only TWO of the remaining three (all empty but not null) are serialized as an empty list '[]' the other is simply omitted. No exceptions are thrown.
Deserialization does not work at all. I use the following code to deserialize the same file I saved. The JSON string is properly read into jsonString
but the deserialization does not throw an exception and yet returns an empty (not null) version of my object with the properties set as the parameterless constructor does. In other words, it is NOT populated with the data contained on the jsonString
.
string jsonString = File.ReadAllText(filename, System.Text.Encoding.UTF8);
db = JsonSerializer.Deserialize<DocumentRegistry>(jsonString);
Am I missing something here? or am I better off with another JSON library (free)?
来源:https://stackoverflow.com/questions/63252221/jsonserializer-silently-fails-to-deserialize-my-object