Skip to content

Serialization options for System.Text.Json support #1107

Description

@brendan-nobadthing

Hi,

I'm looking to serialize a model containing Nodatime types into a jsonb data field.
Right now this serializes a whole bunch of individual fields from the nodatime type.
I see a couple of days ago, jon skeet published a beta for system.text.json serlialisation support for nodatime:
https://www.nuget.org/packages/NodaTime.Serialization.SystemTextJson

This looks like just the thing I'm looking for but I'm not sure how to wire this config into the serialization used by npgsql & EF core.

  • the new system.text.serlializer doe not seem to have the same global default engine that NewtonSoft provided.
  • And I've yet to find any configurable interface to the serializer used by npgsql.

Any ideas / suggestions?
Thanks!

Activity

  1. changed the title [-]Support NodaTime types when serializing to Jsonb fields[/-] [+]Serialization options for System.Text.Json support[/+] on Nov 4, 2019
  2. added this to the 5.0.0 milestone on Nov 4, 2019
  3. roji commented on Nov 4, 2019

    @roji
    Member

    You're correct - in this initial version of JSON support there aren't any hooks for configuring the System.Text.Json serializer. This isn't trivial to do, but I agree it's definitely important.

  4. brendan-nobadthing commented on Nov 10, 2019

    @brendan-nobadthing
    Author

    Hi @roji Thanks for the reply.

    After a bit of digging around, I managed to find a workaround.
    Once I realised that the actual serialization was being done by JsonHandler way down in NpgSql itself, I was able to refer to how the nodatime handlers and mappers are configured to come up with this:

    var origJsonbMapping =
        NpgsqlConnection.GlobalTypeMapper.Mappings.Single(m => m.NpgsqlDbType == NpgsqlDbType.Jsonb);
    NpgsqlConnection.GlobalTypeMapper.RemoveMapping(origJsonbMapping.PgTypeName);
    NpgsqlConnection.GlobalTypeMapper.AddMapping(new NpgsqlTypeMappingBuilder
    {
        PgTypeName = origJsonbMapping.PgTypeName,
        NpgsqlDbType = origJsonbMapping.NpgsqlDbType,
        DbTypes = origJsonbMapping.DbTypes,
        ClrTypes = origJsonbMapping.ClrTypes,
        InferredDbType = origJsonbMapping.InferredDbType,
        TypeHandlerFactory = new JsonbHandlerFactory(new JsonSerializerOptions()
            .ConfigureForNodaTime(DateTimeZoneProviders.Serialization))
    }.Build());

    Works so far for a simple "save stuff, and get the same values back" Integration test. Will report back here if I get any issues once applied to my project.

  5. roji commented on Nov 25, 2019

    @roji
    Member

    @brendan-ssw great :) Note that this will change the ADO-level serialization options, so documents will be read and written with these options. However, EF Core also generates JSON property names when traversing into a JSON column in a LINQ query, and that's not taken care of by the above.

  6. sitepodmatt commented on Jan 3, 2020

    @sitepodmatt

    This is definitely a desired feature for those using their own Converters registered via JsonSerializerOptions.

    @brendan-ssw solution works accepting the caveat about query EFFunctions, thanks

  7. space-alien commented on May 8, 2020

    @space-alien

    Perhaps the Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime plugin should take a dependency on NodaTime.Serialization.SystemTextJson and configure the JSON Serializer for this scenario by default?

    This might be a good interim step that could be released sooner than full configuration options for the JSON serializer.

  8. roji commented on May 8, 2020

    @roji
    Member

    @space-alien I don't think that makes sense - not all users of the NodaTime plugin use System.Text.Json, so there shouldn't be a dependency there. More importantly, the NodaTime plugin wouldn't actually be involved in the serialization in any way, only in the configuration, which again doesn't seem right.

    Fortunately there's at least a workaround as @brendan-ssw posted above, but other than that the provider simply needs to expose a way to configure the JSON serializer...

  9. space-alien commented on May 8, 2020

    @space-alien

    My thinking was more the other way round - or maybe just back to front, depending on one's perspective..!😅

    The NodaTime.Serialization.SystemTextJson package can be thought of as the NodaTime "default/official/recommended" config for System.Text.Json, just delivered as a separate package.

    All users of json columns are implicitly relying on System.Text.Json, since that's the built-in JSON serializer in efcore.pg.

    So, for a user of the NodaTime efcore.pg plugin, who maps a complex model property to a json column, the built-in NodaTime configuration for System.Text.Json is an appropriate and intuitive default.

    If their complex property contains NodaTime types, it's highly likely they will want the JSON serializer to adopt the NodaTime default configuration. If this default configuration is not applied, it's all but certain they will need to apply serializer configuration manually, when this could probably have been avoided.

    The Nodatime efcore.pg plugin does not take any responsibility for serialization in this setup. I don't think the plugin's dependency on NodaTime.Serialization.SystemTextJson would add anything unwarranted, since we're already reliant on both of that package's sub-dependencies, namely NodaTime and System.Text.Json.

    Of course, this is a separate concern to exposing wider configuration options for the JSON serializer, and a user of the NodaTime plugin could still override any default configuration.

    TL;DR: Without bringing in any new sub-dependencies, the Nodatime plugin could apply NodaTime "default" config to the built-in JSON serializer.

    (I think! 😀)

  10. roji commented on May 8, 2020

    @roji
    Member

    All users of json columns are implicitly relying on System.Text.Json, since that's the built-in JSON serializer in efcore.pg.

    That's true, but System.Text.Json is part of the framework and not an additional external dependencies (since netcoreapp3.0). That's one good reason it exists within EFCore.PG and not as a plugin.

    TL;DR: Without bringing in any new sub-dependencies, the Nodatime plugin could apply NodaTime "default" config to the built-in JSON serializer.

    How would that work? Wouldn't the NodaTime plugin (Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime) need to depend on NodaTime.Serialization.SystemTextJson? If not, how do the methods of the latter get called?

  11. space-alien commented on May 8, 2020

    @space-alien

    Ah, so for netcoreapp3.0 this would actually introduce a dependency on System.Text.Json through NodaTime.Serialization.SystemTextJson, as the latter only targets netstandard2.0?

    If that's the case, would this be solved if NodaTime.Serialization.SystemTextJson added a target for netcoreapp3.0?

  12. roji commented on May 8, 2020

    @roji
    Member

    I'm not sure I understand... When targeting netcoreapp3.0, there's no dependency (i.e. nuget package) needed to use System.Text.Json - it's in the box, just like System.Text. I thought you were proposing that Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime take a dependency on NodaTime.Serialization.SystemTextJson in order to configure Npgsql's JSON serialization options to use it...

  13. space-alien commented on May 8, 2020

    @space-alien

    I thought you were proposing that Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime take a dependency on NodaTime.Serialization.SystemTextJson in order to configure Npgsql's JSON serialization options to use it...

    Yes, I am!

    I thought that this wouldn't add any other new dependencies because:

    • NodaTime.Serialization.SystemTextJson only depends on NodaTime and System.Text.Json.
    • And Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime already depends on these two - NodaTime directly; and System.Text.Json is down in Npgsql.

    Since NodaTime.Serialization.SystemTextJson can be thought of an 'official' NodaTime package, I felt it would be reasonable to add it.

    I'm not too hot on this targeting stuff so perhaps I have misunderstood your earlier comments. Would it not be the case that a user would either be targeting netstandard (in which case Npgsql brings in System.Text.Json), or netcoreapp3.0 (in which case it's in the box, as you say)? I'm sorry if I have misunderstood how this works.

  14. roji commented on May 8, 2020

    @roji
    Member

    My problem is with making Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime depend on NodaTime.Serialization.SystemTextJson, since it wouldn't actually need that package or use it for anything except configuring JSON serialization options. Its current role is to change the mappings of of PostgreSQL date/time types (outside of JSON!) to NodaTime CLR types instead of the built-in BCL types - that's quite different and unrelated.

    Also, there are other non-NodaTime needs to configuration System.Text.Json serialization, so something would have to be exposed in any case - once that happens, it doesn't seem like much to ask the user to take a dependency on NodaTime.Serialization.SystemTextJson themselves and do the proper setup.

    I'm sorry if I have misunderstood how this works.

    No worries at all! This is a good conversation.

  15. 46 remaining items

  16. chrisbbe commented on Dec 20, 2023

    @chrisbbe
  17. roji commented on Dec 20, 2023

    @roji
  18. johnbaro commented on Jan 22, 2025

    @johnbaro

    In other words, it's very unlikely that ToJson() will ever fully support JSON serialization options

    If that's the case (which is fine obviously), should it be called out somewhere that this is a limitation, and any possible workarounds.

    In my case, I had to change JSONSerializationOptions to be PascalCased for property names and omit using a JsonStringEnumConverter and that allowed me to filter properly on enum fields of an owned JSON field.

    e.g.

    db.Resources.Where(a => a.TenantId == userService.TenantId && a.Jobs.Any(j =>
                    j.Type == Upload.JobType && j.Value.Status == JobStatus.Completed))....
    // j.Value is a POCO stored using a ValueConverter<T, JsonDocument> with custom serialization options, NOT using in-built `OwnsOne(e => e.Value, v => v.ToJson)`
    // This is required as I need to support polymorphic type serialization
    

    If this was called out prior, It would have saved me significant time.

    I'm happy to submit a PR for the docs

  19. mattbdc commented on Jan 23, 2025

    @mattbdc

    I understand the limitations here in that it would be near impossible to support all customizations but current impl/defaults are not ideal imo, they are leak dotnet naming conventions and enum backing implementations into the database.

    Perhaps if we just had non pascal case and non number enums then customization wouldn't be always required. Maybe even just two paths ToJsonSetting.PascallyDotNetAndOpaqueEnums and ToJsonSetting.RestOfWorldJsonCasingAndSelfExplainingEnums with a disclaimer that's the limit of json options customization available.

  20. marked Camel Case json(b) data #1915 as a duplicate of this issue on Apr 1, 2025
  21. added theissue type on Jun 14, 2025
  22. Angelinsky7 commented on Oct 8, 2025

    @Angelinsky7

    hello @johnbaro i'm trying to do the same as you. could you give use an example of how you configured your owned JSON field to specify a custom jsonSerializer for a property.
    I sadly cannot find a way to do it correctly.
    Thanks !

  23. johnbaro commented on Oct 14, 2025

    @johnbaro

    @Angelinsky7

    hello @johnbaro i'm trying to do the same as you. could you give use an example of how you configured your owned JSON field to specify a custom jsonSerializer for a property. I sadly cannot find a way to do it correctly. Thanks !

    Apologies, I didn't see this before now.
    I've actually moved on from using npgsql directly and now use Marten instead (although that uses npgsql) so I hope I capture everything that worked here.

    1. I setup a custom JsonSerializerOptions that approximately as in **1
    2. This JsonSerializerOptions is then passed to npgsql in startup as in **2
    3. I'm not sure if this is relevant for your case, but I also have a custom DefaultJsonTypeInfoResolver which is added to my JsonSerializerOptions **3

    I apologise for the messy code dumps, it's not very clean as it's internal code that's grown organically over time 😳

    **1

    // instance
    _dbSerializationOptions = new(() =>
            new JsonSerializerOptions().SetDefaultSerializationOptions(camelCaseNames: false,
                converterExcludeType: typeof(JsonStringEnumConverter)));
    
    // setup
    public static JsonSerializerOptions SetDefaultSerializationOptions(this JsonSerializerOptions options,
            Type? converterExcludeType = null, bool camelCaseNames = true, bool pretty = true,
            JsonConverter[]? converters = null,
            IJsonTypeInfoResolver? overrideTypeResolver = null, bool useRelaxedEncoding = false)
        {
            options.PropertyNamingPolicy = camelCaseNames ? JsonNamingPolicy.CamelCase : null;
            options.PropertyNameCaseInsensitive = true;
            options.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
            options.WriteIndented = pretty;
            if (useRelaxedEncoding) options.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
            if (converters != null)
                foreach (var converter in converters)
                    options.Converters.Add(converter);
    
            if (converterExcludeType == null || converterExcludeType != typeof(JsonStringEnumConverter))
                options.Converters.Add(new JsonStringEnumConverter());
    
            options.TypeInfoResolver = overrideTypeResolver ?? JsonTypeInfoResolver;
            options.AllowOutOfOrderMetadataProperties = true;
            return options;
        }

    **2

    // snip
        services.AddDbContext<DataContext>(options =>
            {
                  options.UseNpgsql(conBuilder.ConnectionString, o =>
                        o.ConfigureDataSource(ds =>
                                ds.EnableDynamicJson()
                                    .ConfigureJsonOptions(JsonSerializationUtilities.DBSerializationOptions))
                            .UseNodaTime())
    // .....

    **3

    public class CustomJsonTypeResolver : DefaultJsonTypeInfoResolver
    {
        public override JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options)
        {
            var jsonTypeInfo = base.GetTypeInfo(type, options);
    
            if (jsonTypeInfo.Type == typeof(Job))
                jsonTypeInfo.PolymorphismOptions = new JsonPolymorphismOptions
                {
                    IgnoreUnrecognizedTypeDiscriminators = true,
                    UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType,
                    DerivedTypes =
                    {
                        new JsonDerivedType(typeof(Upload), nameof(Upload))
                    }
                };
    // .....
  24. mattbdc commented on Oct 15, 2025

    @mattbdc

    There is also XO.EntityFrameworkCore.NpgsqlJsonSerializerOptions which gives you querying into jsonb columns that don't have the DotNetNamingInstanity default, you can use this XO library to use a sane Json options setup such as JsonSerializaitonOptions.Web or your own version.

    Once you have your JSO you need to register with the data source using ConfigureJsonOptions(myJSO), as you have to already, and also with the context with UseNpgsqlJsonSerializationOptions, this latter extension method is provided by XO which is what allows you to get some query ability into jsonb objects that dont use DotNamingAndCasingThatNoOneElseUses..

    This isn't for ToJson() new stuff in EF 9.0 but at least takes the old way a good way there..

    Also its best adopt XO into your own project and upgrade the dependencies, there was no changes or very tiny changes required, not enough to fork it

  25. BaconSoap commented on Jan 22, 2026

    @BaconSoap

    I ran into this issue too when adopting JSONB + ToJson() columns, and wrote up a guide + code on how I solved it:

    • camelCase property names + camelCase string enums
    • full ToJson/query support
    • avoids manually annotating individual properties with JsonPropertyName
    • keeps us in the npgsql + EF zone-of-joy

    Using this, I can persist/query JSON in the same format used throughout the rest of my stack.

    it uses reflection for the enum behavior, but should otherwise be AOT compatible (and smarter people can make a source generator 😸 )

    https://gist.github.com/BaconSoap/6df6cfec06e819858853f6a25509084c


    Reading through the chain it makes sense how the ToJson implementation inherits EFCore pain points, but as others have mentioned, the npgsql docs make this a bit of a noob trap for devs adopting the feature. They suggest to use ToJson instead of the JsonDocument approach, but without warning that it does its own thing/uses EFs internals vs the default serializer. It would have saved some time to point to this issue, or to note that the serializer settings won't apply by default.


    Thank you for the library and support!

  26. mattbdc commented on Feb 27, 2026

    @mattbdc

    @BaconSoap

    I'm not sure a queue is required here, the above also breaks in a few scenarios due to using seenTypes for the exit condition, for example:

    public class SaleOrder {
     public Address BillingAddress { get; set; }
     public Address ShippingAddress { get; set; }
    }

    Since we don't care about weather its depth or breadth first, a simple bit of recursion can fix and simplify this:

      public static ComplexPropertyBuilder<T> ToArborJson<T>(this ComplexPropertyBuilder<T> builder,
        string? jsonColumnName = null)
      {
        builder.ToJson(jsonColumnName);
    
        static void FixProperties(IMutableComplexProperty metadata)
        {
          foreach (var scalarProperty in metadata.ComplexType.GetProperties())
          {
            scalarProperty.SetJsonPropertyName(scalarProperty.Name.ToCamelCase());
    
            if (scalarProperty.ClrType.IsEnum)
            {
              var converterType =
                typeof(EnumToCamelCaseStringConverter<>).MakeGenericType(scalarProperty.ClrType);
              var converter = Activator.CreateInstance(converterType, null);
              scalarProperty.SetValueConverter((ValueConverter)converter);
            }
          }
    
          foreach (var complexProp in metadata.ComplexType.GetComplexProperties())
          {
            complexProp.SetJsonPropertyName(complexProp.Name.ToCamelCase());
            FixProperties(complexProp);
          }
        }
    
        FixProperties(builder.Metadata);
        return builder;
      }

    .. I ultimately ended up going back to the old way though , ComplexProperty/ToJson() doesn't seem to support complex types that might contain a dictionary property annotated with JsonExtensionData to slurp up unknown keys/values which does work when plumbing your own serializers the old way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions