Home > database >  How to map fields name in jsonb field to another name in object?
How to map fields name in jsonb field to another name in object?

Time:01-15

I use Postgres and I have DB with a table that looks like that

column - foo
type - jsonb
value - {"baz" : "test" }

Please notice that "baz" is not capitalized (pretty much this json document will be in a camelCase).

I have the code in C# (so the naming convention is Pascal Case)

public class Foo
{
     [Column(TypeName = "jsonb")]
     public BarData Bar { get; set; }
}

public class BarData
{
   // ??? What kind of annotation to put here
   public String Baz { get; set; }
}

I use entity framework npgsql to read/write to DB. Unfortunately, when npgsql read from DB, it won't populate Baz (because the naming convention doesn't match)

a) I tried to use [Column("baz")]. However, it's ignored (probably because it's not really a column, but a json tag)

b) I was considering naming the property "baz", but it just shifts a problem to another place in the code (where another mapping needs to be done).

As a result, I am looking whether I missed some way to do it case-insensitive or map the property to the name which comes from json.

CodePudding user response:

npgsql driver uses System.Text.Json for serializing json values. So all you need is to annotate your property with JsonPropertyName attribute.

public class BarData
{
   [JsonPropertyName("baz")]
   public String Baz { get; set; }
}

If your only concern is casing you can use JsonSerializerSettings.PropertyNamingPolicy

This is how you change serialization options as of version 6.0 :

var options = new JsonSerializerOptions
{
    // Customize based on needs...
};
NpgsqlConnection.GlobalTypeMapper.AddTypeResolverFactory(new JsonOverrideTypeHandlerResolverFactory(options));

Credits to this github answer

Also worth mentioning that the second workaround won't affect the query generation.

  •  Tags:  
  • Related