我试图从数据库中获取部分数据,然后序列化它(工作很好)。当我试图反序列化该数据时,抛出JsonSerializationException。
DbGeography geoPoint = CreatePoint(40.7056308, -73.9780035);
string serializedPoint = JsonConvert.SerializeObject(geoPoint);
DbGeography resjson = JsonConvert.DeserializeObject<DbGeography>(serializedPoint);
这是CreatePoint方法:
public static DbGeography CreatePoint(double latitude, double longitude)
{
string text = string.Format(CultureInfo.InvariantCulture.NumberFormat,
"POINT({0} {1})", longitude, latitude);
return DbGeography.PointFromText(text, 4326);
}
我在控制台应用程序中产生了这个错误。
Nuget Packages installed:
EntityFramework 6.1.0
Newtonsoft.Json 6.0.3
有人知道我做错了什么吗?
System.Data.Spatial.DbGeography
(我假设您正在使用)不适合Newtonsoft.Json的反序列化。您没有提到抛出的异常,但我观察到的异常是:
找不到用于类型的构造函数System.Data.Spatial.DbGeography。类应该有默认值构造函数,一个带参数的构造函数或一个带标记的构造函数
您可以通过使用JsonConverter
自己提供序列化/反序列化逻辑来解决这个问题。我用的是JSON。Net JsonConverter for DbGeography,并稍微修改它以修复我的本地文化(使用','作为小数分隔符)的错误:
public class DbGeographyConverter : JsonConverter
{
private const string LATITUDE_KEY = "latitude";
private const string LONGITUDE_KEY = "longitude";
public override bool CanConvert(Type objectType)
{
return objectType.Equals(typeof(DbGeography));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return default(DbGeography);
var jObject = JObject.Load(reader);
if (!jObject.HasValues || (jObject.Property(LATITUDE_KEY) == null || jObject.Property(LONGITUDE_KEY) == null))
return default(DbGeography);
string wkt = string.Format(CultureInfo.InvariantCulture, "POINT({1} {0})", jObject[LATITUDE_KEY], jObject[LONGITUDE_KEY]);
return DbGeography.FromText(wkt, DbGeography.DefaultCoordinateSystemId);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var dbGeography = value as DbGeography;
serializer.Serialize(writer, dbGeography == null || dbGeography.IsEmpty ? null : new { latitude = dbGeography.Latitude.Value, longitude = dbGeography.Longitude.Value });
}
}
你可以这样使用它:
DbGeography geoPoint = CreatePoint(40.7056308, -73.9780035);
string serializedPoint = JsonConvert.SerializeObject(geoPoint, new DbGeographyConverter());
DbGeography resjson = JsonConvert.DeserializeObject<DbGeography>(serializedPoint, new DbGeographyConverter());