1

I'm storing domain objects as JSON in the database. To store DDD value objects I need to create a JsonConverter. I'm trying to create a generic value object converter in System.Text.Json.

I have seen the following related questions in SO and EventFlow implementation :

So how to create a generic value object JsonConverter in System.Text.Json without having a performance penalty.

Edit: To add some context, this is the entity:

public class Meeting : Entity
{
    public MeetingId Id { get; private set; }
    public string Title { get; private set;}
    private MeetingTerm Term { get; private set;}
    ... // other properties
}

public class MeetingTerm : ValueObject
{
    public DateTime StartDate { get; }

    public DateTime EndDate { get; }
    ... // other properties
}

public class MeetingId : ValueObject
{
    public Guid Id { get; }
    ... // other properties
}

I want to serialize it as:

{
    "id": "unique-guid",
    "title": "foo",
    "startDate": "foo",
    "endDate": "bar"
    ... // other properties
}
rebornx
  • 407
  • 6
  • 21
  • _"To store DDD value objects I need to create a JsonConverter"_ Why is that? Isn't the System.Text.Json API already generic? Why do you need some `JsonConverter`? And why do you have links related to Json.NET? – Guru Stron Jun 03 '21 at 13:08
  • @GuruStron I have updated the question with an example, hope that helps to answer your queries. – rebornx Jun 03 '21 at 13:45
  • So, you might as well build a new model that takes a `Meeting` instance as input and extracts *some* of the property values of its objects. Or do you want a to build a method / Converter, that takes **all** the property values and objects from `Meeting` and returns all property values (discarding the objects) as a new, single, object? – Jimi Jun 03 '21 at 14:37
  • Can you confirm that what you want to do for a class derived from `ValueObject` is to bubble all of it serializable properties up to the container object? If so, there's no easy way to do that with `System.Text.Json` as it [does not provide access to its internal serialization contract information](https://stackoverflow.com/q/58926112/3744182)... – dbc Jun 03 '21 at 19:37
  • 1
    So you will basically have to write your own serializer. And if you don't want a performance penalty that means doing something like compiling your own expressions. I don't really recommend it as it's a lot of work, but to get started you could look at [Custom JSON serializer for optional property with System.Text.Json](https://stackoverflow.com/a/63431434/3744182). – dbc Jun 03 '21 at 19:38
  • @Jimi I'm looking for a converter. – rebornx Jun 04 '21 at 03:31
  • @dbc Yes, the class derived from ValueObject is to bubble all of it serializable properties up to the container object. You can see `SingleValueObjectConverter` which does the same but only for a single property. – rebornx Jun 04 '21 at 03:34

0 Answers0