c# – 使用Newtonsoft.Json反序列化DbGeometry

前端之家收集整理的这篇文章主要介绍了c# – 使用Newtonsoft.Json反序列化DbGeometry前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在按照John Papa在他最新的PluralSight课程中概述的方法,使用Angular,Breeze和Web API 2构建SPA.

一切顺利,我可以将信息,更新,插入,删除回服务器.但是我使用的是空间类型,当我尝试更新具有空间类型的实体时,会得到以下错误

An exception of type ‘Newtonsoft.Json.JsonSerializationException’ occurred in
Newtonsoft.Json.dll but was not handled in user code

Additional information: Error getting value from ‘WellKnownValue’ on
‘System.Data.Entity.Spatial.DbGeometry’.

内部异常似乎指出,WellKnownValue为null,它不是,因为我已经检查发送到服务器的JSON,然后发送到Breeze ContextProvider并使用SaveChanges方法保存Well事实.

{
"entities": [
 {
  "TableKey": 2,"CaseName": "Mikhail Lermontov","StartDate": "2013-06-11T00:00:00Z","EndDate": null,"IsCurrent": true,"SRID": 109,"Shape": {
    "$id": "2","$type": "System.Data.Entity.Spatial.DbGeometry,EntityFramework","Geometry": {
      "$id": "3","$type": "System.Data.Entity.Spatial.DbGeometryWellKnownValue,"CoordinateSystemId": 2193,"WellKnownText": "POLYGON ((1695943 5462665,1713098 5462665,1713098 5449659,1695943 5449659,1695943 5462665))"
    }
  },"SpillLocation": "Marlborough Sounds","Image": "http://www.nzmaritime.co.nz/images/lm5.jpg\r\n","DefaultBaseMapKey": 2,"__unmapped": {
    "isPartial": false
  },"entityAspect": {
    "entityTypeName": "DatSpillCase:#Osiris.Model","defaultResourceName": "DatSpillCases","entityState": "Modified","originalValuesMap": {
      "CaseName": "Mikhail Lermontov"
    },"autoGeneratedKey": {
      "propertyName": "TableKey","autoGeneratedKeyType": "Identity"
    }
  }
}
 ],"saveOptions": {}
}

所以我的问题是,可以在NewtonSoft库中反序列化DbGeometry类型,如果没有,那么有什么建议可以解决.

解决方法

System.Data.Spatial.DbGeometry不能很好地与Newtonsoft.Json

您需要创建一个JsonConverter来转换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);
        }
    }

然后在您的模型的属性添加属性

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

现在,当您点击BreezeController时,反序列化将由我们的新DbGeometryConverter处理.

希望它有帮助.

原文链接:https://www.f2er.com/csharp/94085.html

猜你在找的C#相关文章