DbGeometry serialization issue in Asp.net web api

I am creating an OData v3 web API with the first Entity Framework 6.0 interface.

Everything works well, and I can do CRUD operations back to the api server.

However, I use spatial types, and some of my objects have DbGeometry properties. When I try to update / send an object of type DbGeometry from a client application (just a console application for tests), I get this DataServiceRequestException:

There is no constructor without parameters for this object.

It took me a while, but I defined the DbGeometry type as responsible. I already covered this topic here and made a custom JsonConverter where I applied the property:

 [Required] [JsonConverter(typeof(DbGeometryConverter))] [Column("geometria")] public DbGeometry Geometria { get; set; } 

This did not work. An object will not be deserialized on the api web server unless I remove the DbGeometry property.

I also tried changing the behavior of the global json serializer

 var formatters = GlobalConfiguration.Configuration.Formatters; var jsonFormatter = formatters.JsonFormatter; jsonFormatter.SerializerSettings.Converters.Add(new DbGeometryConverter()); 

Also useless. I really need DbGeometry properties. What else can I do to get around this?

+5
source share
1 answer

A little late, but for those who will seek the answer:

I managed to do this using the same code at the controller level. The idea was taken from this SO Question & Answer.

So here is the code including the DbGeometryConverter.

DbGeometryConverter.cs:

 public class DbGeometryConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType.IsAssignableFrom(typeof(DbGeometry)); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var location = JObject.Load(reader); var token = location["Geometry"]["WellKnownText"]; string geom = token.ToString(); token = location["Geometry"]["CoordinateSystemId"]; int srid = token != null ? int.Parse(token.ToString()) : 0; var converted = DbGeometry.FromText(geom, srid); return converted; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } public override bool CanWrite => false; } 

CustomJsonAttribute.cs:

 public class CustomJsonAttribute : Attribute, IControllerConfiguration { public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor) { var formatter = controllerSettings.Formatters.JsonFormatter; formatter.SerializerSettings.Converters.Add(new DbGeometryConverter()); } } 

And the [CustomJson] attribute on the controller that uses DbGeometry.

0
source

Source: https://habr.com/ru/post/1208666/


All Articles