question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] v5 Example of how to use custom serializers?

See original GitHub issue

Hello, I’m a newbie to LiteDB and currently evaluating it for my purposes. I’ve tried to refer to the documentation, however it seems a lot of it is for v4 which is apparently out-of-date?

My question related to whether there is a concrete example of how to perform a customized de/serialization of any object.

My classes will be used by external developers, so I do not wish to decorate classes with LiteDB-specific tags.

As such, how would I go about persisting a class such as this:

public class Record 
{
   string Field1 {get; set;}
   string Field2 {get; set;}
   [NonSerialized]
   string DontPersistField { get; set; }
}

Note that the class has no ‘Id’ field and I would like to omit ‘DontPersistField’ from being stored (it is marked as ‘NonSerialized’).

What is the correct way of persisting this in LiteDB without having to alter my class structure?

Thanks!

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5

github_iconTop GitHub Comments

3reactions
lbnascimentocommented, Mar 30, 2020

@devmaestro1 If you want a solution that ignores fields with NonSerializedAttribute and works for any type, you could create a custom mapper class that inherits from BsonMapper and overrides GetTypeMembers:

public class MyMapper : BsonMapper
{
    protected override IEnumerable<MemberInfo> GetTypeMembers(Type type)
    {
        return base.GetTypeMembers(type).Where(m => !m.IsDefined(typeof(NonSerializedAttribute), true));
    }
}

//Usage
var mapper = new MyMapper();
mapper.IncludeFields = true; //the mapper only serializes properties by default
                             //this command is needed to serialize fields too
using var db = new LiteDatabase("database.db", mapper);

  • Is there an intention to support standard “ISerialization”-type functionality and attributes (eg. Serialize/Deserialize)?
  • Is there any interface supported by LiteDb (such as “ISerializable”) that would allow each class to define how it should be serialized rather than having it centralized in the Mapper class?

LiteDB does not support these features currently, however they could be considered for the future.

  • Is there any method that is called after serialization/deserialization so I can perform any additional “cleanup” tasks on the object prior to its use?

You could achieve this with custom serializers and deserializers:

mapper.RegisterType<MyClass>
(
    serialize: o =>
    {
        var doc = new BsonDocument();
        doc["_id"] = o.Id;
        doc["Field1"] = o.Field1;
        //whatever you want to do
        return doc;
    },
    deserialize: doc =>
    {
        var o = new MyClass();
        o.Id = doc["_id"];
        o.Field1 = doc["Field1"];
        //whatever you want to do
        return o;
    }
);
0reactions
devmaestro1commented, Mar 31, 2020

Thank you very much for your response on this. It has really helped me understand LiteDB a lot better.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Custom serializers and deserializers in LiteDB v5.0.9
The release notes for LiteDB 5.0. 9 says, "Custom serializers and deserializers can now be used even with basic BSON types. This is...
Read more >
Jackson - Custom Serializer
This article illustrated how to get to a custom JSON output with Jackson 2, by using Serializers. The implementation of all these examples...
Read more >
The Serializer Component (Symfony Docs)
This article explains the philosophy of the Serializer and gets you familiar with the concepts of normalizers and encoders. The code examples assume...
Read more >
How to use sessions
You can use the SESSION_SERIALIZER setting to customize the session serialization format. Even with the caveats described in Write your own serializer, ...
Read more >
Working With JSON Data in Python
In this tutorial you'll learn how to read and write JSON-encoded data using Python. You'll see hands-on examples of working with Python's built-in...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found