Question Details

No question body available.

Tags

c# json postgresql entity-framework-core automapper

Answers (1)

Accepted Answer Available
Accepted Answer
October 20, 2025 Score: 4 Rep: 80,895 Quality: Expert Completeness: 80%

You could use the following function to validate JSON.

private bool IsValidJson(string? json) { if (string.IsNullOrWhiteSpace(json)) return false;

var utf8 = Encoding.UTF8.GetBytes(json); var utf8Reader = new Utf8JsonReader(utf8); if (!JsonDocument.TryParseValue(utf8Reader, out var doc)) return false;

doc?.Dispose(); return true; }

Then

.ForMember(dest => dest.RuleJson, opt => opt.MapFrom(src => IsValidJson(src.RuleJson) ? src.RuleJson : null))

If you already have a JsonDocument then you should pass that instead, rather than stringifying it, as noted in the documentation.


Note that in your model you should specify the column type for jsonb

[Column(TypeName = "jsonb")] public string? RuleJson { get; set; } // jsonb column in PostgreSQL