Serialize and Deserialize JSON on model fields

.net-core c# entity-framework-core json postgresql

Question

My model looks like this:

public class Person
    {
        public Guid Id { get; set; } = Guid.NewGuid();

        public string Name { get; set; }
        public string Job { get; set; }

        [Column(TypeName = "jsonb")]
        public JObject Address { get; set; }

    }

As you can see, Address is a jsonb column. Right now, the client has to turn its contents into JSON for the server to accept it, and parse the JSON contents when it retrieves it from the server. What is an elegant approach to have the server take care of this work?

1
0
3/19/2020 1:39:18 AM

Popular Answer

The best approach I found was to add something like this to my DbContext

modelBuilder.Entity<Person>()
            .Property(e => e.Address)
            .HasConversion(
                v => JsonConvert.SerializeObject(v,
                    new JsonSerializerSettings {ContractResolver = new CamelCasePropertyNamesContractResolver()}),
                v => JsonConvert.DeserializeObject<JObject>(v,
                    new JsonSerializerSettings {ContractResolver = new CamelCasePropertyNamesContractResolver()})
            );
0
3/19/2020 1:39:04 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow