Deserializing DbGeometry with Newtonsoft.Json

后端 未结 3 600
挽巷
挽巷 2021-02-13 19:22

I\'m building a SPA using Angular,Breeze and Web API 2 following the approach as outlined by John Papa in his latest PluralSight course.

Everything works well and I can

3条回答
  •  梦毁少年i
    2021-02-13 19:47

    System.Data.Spatial.DbGeometry does not play nicely with Newtonsoft.Json

    You need to create a JsonConverter to convert the DbGeometry

    public class DbGeometryConverter : JsonConverter
        {
            public override bool CanConvert(Type objectType)
            {
                return objectType.IsAssignableFrom(typeof(string));
            }
    
            public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            {
                JObject location = JObject.Load(reader);
                JToken token = location["Geometry"]["WellKnownText"];
                string value = token.ToString();
    
                DbGeometry converted = DbGeometry.PolygonFromText(value, 2193);
                return converted;
            }
    
            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
                // Base serialization is fine
                serializer.Serialize(writer, value);
            }
        }
    

    Then on your property in your model add the attribute

    [JsonConverter(typeof(DbGeometryConverter))]
    public DbGeometry Shape { get; set; }
    

    Now when you hit your BreezeController the deserialization will be handled by our new DbGeometryConverter.

    Hope it helps.

提交回复
热议问题