LiteDB icon indicating copy to clipboard operation
LiteDB copied to clipboard

Deserialize dictionary key with TypeDescriptor

Open Joy-less opened this issue 1 year ago • 4 comments

BsonDocument only supports string keys. Since Dictionary is serialized as BsonDocument, certain types don't work as keys.

This pull request converts the keys to the correct type when deserializing, using the method in #588.

For example, the key d396d0e8-2763-4ad6-a1c0-f19f254576ec can now be deserialized as a Guid.

This isn't really ideal but it does the job.

Fixes #546 and #2161. Replaces #588.

Joy-less avatar Nov 22 '24 02:11 Joy-less

Hi @Joy-less

Great job on the changes! Would it be possible to also implement and ensure the following works as expected?

public class DataContainer
{
    public Dictionary<(int, string), string> DataDict { get; set; }
}

Additionally, as mentioned earlier on Discord, reviewing a PR becomes challenging when it includes unrelated changes (e.g., refactor-renames). For future submissions, keeping PRs focused on a single purpose would help simplify the review process.

Thank you for your efforts on this!

JKamsker avatar Dec 01 '24 21:12 JKamsker

Would it be possible to also implement and ensure the following works as expected?

public class DataContainer
{
    public Dictionary<(int, string), string> DataDict { get; set; }
}

This does not work as expected. The key should be serialized as JSON for something complex like this. However, that would break compatibility, so it might be a good idea to assume it's a string key if it fails to deserialize as JSON.

Joy-less avatar Dec 01 '24 22:12 Joy-less

I've changed the pull request to serialize the key as JSON if it's not a string. One of the tests was failing because of how LiteDB truncates DateTimes to the nearest millisecond. To keep JsonSerializer consistent with BufferWriter, I changed the test so now it accepts the truncated value as well. All tests passed now.

Joy-less avatar Dec 01 '24 23:12 Joy-less

@Joy-less Thanks for the changes! Can you think of an scenario where the deserialization doesnt work on databases created with a prior (released) version of litedb?

JKamsker avatar Dec 01 '24 23:12 JKamsker