Skip to content

Relational: Allow a custom serializer for JSON columns #28043

Description

@AndriySvyryd

Related to #17306

Activity

  1. added this to the Backlog milestone on May 17, 2022
  2. changed the title [-]Allow a custom serializer for JSON columns[/-] [+]Relational: Allow a custom serializer for JSON columns[/+] on May 17, 2022
  3. SaifAqqad commented on Sep 19, 2023

    @SaifAqqad

    Is this still planned for release with .NET 8?

  4. LuohuaRain commented on Sep 22, 2023

    @LuohuaRain

    Is this still planned for release with .NET 8?

    I'd like to know as well.

  5. modified the milestone: Backlog on Sep 26, 2023
  6. ajcvickers commented on Oct 3, 2023

    @ajcvickers
    Contributor

    @SaifAqqad @LuohuaRain We made significant changes to the JSON infrastructure in 8, which means some additional design is now needed to expose customization of what is now already a custom serialization mechanism.

  7. 9 remaining items

  8. shahrzadabedi commented on Oct 25, 2023

    @shahrzadabedi

    @shahrzadabedi Not currently. I filed #32152 to track this.

    Thanks Arthur

  9. shahrzadabedi commented on Oct 25, 2023

    @shahrzadabedi

    @wjrogers the Npgsql provider's support for JSON which this affects is very different from the EF owned entity support for JSON (ToJson()) that's discussed here. For 8.0 I'm working on bringing the latter into Npgsql as well.

    Thank you for the clarification, Shay.

  10. wizofaus commented on Jan 23, 2024

    @wizofaus

    Definitely need this - I was hoping to use built-in JSON serialization, but it's not handling badly formed data well at all (the exceptions don't even tell me where the error is!).
    But none of the JsonConvertor (or other Json-) attributes I'm adding seem to be getting acknowledged at all.

  11. romanov commented on Jan 26, 2024

    @romanov

    Is there any temp solution for now? Like global setting, or EF uses built-in serialization?

  12. wizofaus commented on Jan 27, 2024

    @wizofaus

    I got it working the way I needed using

            public static Builders.PropertyBuilder<T> HasJsonConversion<T>(this Builders.PropertyBuilder<T> propertyBuilder) where T : class, new()
            {
                ValueConverter<T, string> converter = new ValueConverter<T, string>
                (
                    v => JsonSerializer.Serialize(v, default(JsonSerializerOptions)),
                    v => JsonSerializer.Deserialize<T>(v, new JsonSerializerOptions { NumberHandling = JsonNumberHandling.AllowReadingFromString }) ?? new T()
                );
                propertyBuilder.HasConversion(converter);
                propertyBuilder.Metadata.SetValueConverter(converter);
                return propertyBuilder;
            }
    

    which you can use in the OnModelCreating as needed, e.g.:

    modelBuilder.Entity<MyRowType>().Property(expr=> expr.JsonField).HasJsonConversion();

    That way it honors all the attributes that normally work to control JSON serialisation (though it doesn't allow using DI-managed JsonSerializerOptions).

  13. dev-mfm commented on Jul 23, 2024

    @dev-mfm

    I got it working the way I needed using

            public static Builders.PropertyBuilder<T> HasJsonConversion<T>(this Builders.PropertyBuilder<T> propertyBuilder) where T : class, new()
            {
                ValueConverter<T, string> converter = new ValueConverter<T, string>
                (
                    v => JsonSerializer.Serialize(v, default(JsonSerializerOptions)),
                    v => JsonSerializer.Deserialize<T>(v, new JsonSerializerOptions { NumberHandling = JsonNumberHandling.AllowReadingFromString }) ?? new T()
                );
                propertyBuilder.HasConversion(converter);
                propertyBuilder.Metadata.SetValueConverter(converter);
                return propertyBuilder;
            }
    

    which you can use in the OnModelCreating as needed, e.g.:

    modelBuilder.Entity<MyRowType>().Property(expr=> expr.JsonField).HasJsonConversion();

    That way it honors all the attributes that normally work to control JSON serialisation (though it doesn't allow using DI-managed JsonSerializerOptions).

    I tried your solution but it didn't work.

  14. wizofaus commented on Jul 27, 2024

    @wizofaus

    Didn't work in what sense? Don't have access to the codebase I was working on where I did that now but it was definitely doing the job for me.

  15. added theissue type on Jun 15, 2025
  16. Cubody commented on Jun 19, 2025

    @Cubody

    I got it working the way I needed using

            public static Builders.PropertyBuilder<T> HasJsonConversion<T>(this Builders.PropertyBuilder<T> propertyBuilder) where T : class, new()
            {
                ValueConverter<T, string> converter = new ValueConverter<T, string>
                (
                    v => JsonSerializer.Serialize(v, default(JsonSerializerOptions)),
                    v => JsonSerializer.Deserialize<T>(v, new JsonSerializerOptions { NumberHandling = JsonNumberHandling.AllowReadingFromString }) ?? new T()
                );
                propertyBuilder.HasConversion(converter);
                propertyBuilder.Metadata.SetValueConverter(converter);
                return propertyBuilder;
            }
    

    which you can use in the OnModelCreating as needed, e.g.:

    modelBuilder.Entity<MyRowType>().Property(expr=> expr.JsonField).HasJsonConversion();

    That way it honors all the attributes that normally work to control JSON serialisation (though it doesn't allow using DI-managed JsonSerializerOptions).

    This works, but as long as we don't expect a correct LINQ->SQL translation(mapping of columns inside POCO to json functions vars) with the modified Case (snake_case for ex).
    The same thing was said here:
    npgsql/efcore.pg#1107 (comment)

    Any workarounds (except using JsonPropertyNameAttribute)?

  17. DarkGraySun commented on Jul 7, 2025

    @DarkGraySun

    I need a way to ignore properties with null values ​​in serialization. This would allow me to use completely different properties in different environments without unnecessary overhead in the database. Serialization options would be very important for this. LINQ->SQL translation is essential.

  18. lonix1 commented on Jan 19, 2026

    @lonix1

    To expand on the previous comment... We don't want to persist nulls, because it wastes space, e.g. "{ ""Foo"": null, ""Bar"": null, ""Baz"": null, ""Qux"": null, ..., ""Something"": ""Hello"" }". That's a simple example, but data serialised as JSON is often of the "bag of stuff" variety which may have many properties.

    And it does not honour [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)], so there's no way to prevent that behaviour without reconfiguring the entire context.

    Our workaround is to avoid ToJson(), and use the old way instead:

    var options = new JsonSerializerOptions {
      DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,       // <-----
    };
    
    builder.Property(x => x.Cat)
      .HasColumnType("jsonb")
      .HasConversion(
        new ValueConverter<Animal, string>(
          x => JsonSerializer.Serialize(x, options),
          x => JsonSerializer.Deserialize<Animal>(x, options)
        ),
        new ValueComparer<Animal>(...)
      );

    Other than the extra complexity, another downside is we can't query those properties.

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions