gpt4 book ai didi

c# - Web Api 忽略 DbGeography 的自定义 JsonConverter

转载 作者:行者123 更新时间:2023-11-30 16:49:00 24 4
gpt4 key购买 nike

Major 对此很挣扎。所以我试图将嵌套的 Json 数据发送到我的 web api。我的 DbGeography 类型有一个自定义子转换器。但是,当我发送请求时,似乎从未调用过我的自定义转换器。我收到错误消息:无法将对象类型对象转换为 DbGeography。我正在为我的数据模型使用数据库优先 EF。注释掉 locationAccountCreated 属性,其他一切正常,数据成功保存到数据库。

如有任何帮助,我们将不胜感激。

相关请看下方代码

Controller

[Route("Create")]
[HttpPost]
public HttpResponseMessage PostNewAccount([FromBody]IDictionary<string, object> formData)
{
if (formData != null)
{
var nValueCol = formData;

var account = new Account()
{
Email = (string)nValueCol["email"],
Password = (string)nValueCol["password"],
AgreedToTerms = Convert.ToBoolean(nValueCol["agreesToTerms"]),
LocationAccountCreated = (DbGeography)nValueCol["userLocation"]//source of error
//LocationAccountCreated = (DbGeography)(IDictionary<string, IDictionary<string, double>>)nValueCol["userLocation"]
};

//...rest of code unrelated to problem
}

自定义转换器

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) // checks if token is null.
{
return default(DbGeography);
}

var jObject = JObject.Load(reader);

if (!jObject.HasValues || (jObject.Property(LATITUDE_KEY)) == null || (jObject.Property(LONGITUDE_KEY)) == null) //checks if Json Object is null, and if longitude or latitude properties are null
{
return default(DbGeography);
}

string wellKnownText = string.Format("POINT({0} {1})", jObject[LATITUDE_KEY], jObject[LONGITUDE_KEY]);
return DbGeography.FromText(wellKnownText, 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 });
}
}


public class QueryLocationMetadata
{
[JsonConverter(typeof(DbGeographyConverter))]
public virtual System.Data.Entity.Spatial.DbGeography LocationAccountCreated { get; set; }
}

部分类

[MetadataType(typeof(QueryLocationMetadata))]
public partial class Account
{
}

全局.asax

protected void Application_Start()
{
var config = GlobalConfiguration.Configuration;

//Registering routes from the WebApi.Config file
GlobalConfiguration.Configure(Config.WebApiConfig.Register);


//Registering Autofac
GlobalConfiguration.Configure(Config.AutofacConfig.Initialize);

//Registering Formatter
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new DbGeographyConverter());
}

fiddler 请求

http://localhost:9576/Account/Create

User-Agent: Fiddler
Content-type: application/json
Host: localhost:9576
Content-Length: 316


{
"email":"e02f6rt7fgvujtgv@myuct.ac.za",
"firstName":"myFName",
"lastName":"myFName",
"dateOfBirth":"1992-02-18",
"password":"password",
"agreesToTerms":true,
"userName" : "Cool User",
"gender" : "Female",
"userLocation": {"geopoint":{"latitude" : 40.334910, "longitude" : -32.254586}}
}

最佳答案

尝试将其作为第一个提供者插入:

config.Formatters.JsonFormatter.SerializerSettings.Converters.Insert(0, new DbGeographyConverter());

我在 Web Api 2 Controller 中使用您的转换器代码尝试过此操作,如下所示:

public void Post([FromBody]System.Data.Entity.Spatial.DbGeography value)

还要注意数字格式问题。 WKT 部分可能需要看起来像这样:

string wellKnownText = string.Format("POINT({0} {1})", jObject[LATITUDE_KEY].Value<double>().ToString(System.Globalization.NumberFormatInfo.InvariantInfo), jObject[LONGITUDE_KEY].Value<double>().ToString(System.Globalization.NumberFormatInfo.InvariantInfo));

关于c# - Web Api 忽略 DbGeography 的自定义 JsonConverter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37397204/

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