2016-05-23 38 views
2

與此有關的主要掙扎。所以我試圖將嵌套的Json數據發送到我的web api。我有一個自定義的兒子轉換器,用於我的DbGeography類型。但是,當我發送我的請求時,似乎我的自定義轉換器從未被調用過。我得到錯誤說:無法將對象類型對象轉換爲DbGeography。我爲我的數據模型首先使用數據庫。 註釋掉locationAccountCreated屬性,其他一切正常,數據成功保存到數據庫。Web Api忽略用於DbGeography的自定義JsonConverter

請任何幫助將非常感激。下面

控制器

[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 
} 

定製Conveter

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 
{   
} 

的Global.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()); 
} 

提琴手請求

http://localhost:9576/Account/Create 

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


{ 
    "email":"[email protected]", 
    "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}} 
} 

回答

2

嘗試插入它作爲第一個提供者:

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

我與你的轉換器這樣的代碼嘗試這樣的網絡API 2控制器:

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)); 
+1

Kagelos嗨,我想你的建議,仍然沒有工作,沒有確切知道在哪裏,我就這一個走錯了。當你按照上面的方法試用時,轉換器是否工作? – user6201138