gpt4 book ai didi

c# Json.net DbGeography 反序列化错误

转载 作者:太空狗 更新时间:2023-10-29 22:19:00 28 4
gpt4 key购买 nike

我正在尝试从数据库中获取 Spartial 数据,然后将其序列化(效果很好)。当我尝试反序列化该数据时,会抛出 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 反序列化。你没有提到抛出的异常,但我观察到的是:

Unable to find a constructor to use for type System.Data.Spatial.DbGeography. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute.

您可以通过 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());

关于c# Json.net DbGeography 反序列化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23790459/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com