Serializing a DbGeography type in MVC

雨燕双飞 提交于 2019-12-12 02:05:00

问题


I've got a problem with serializing a DbGeography type. My controller action always gives an error instead of an object.

For purpose of example, here is my class:

public class Centre
{
  public int CentreId { get; set; }

  [Required]
  public string Name { get; set; }

  [Required]
  [JsonConverter(typeof(DbGeographyConverter))]
  public DbGeography Location { get; set; }
}

My DbGeographyConverter class is defined as per many examples around:

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 });
  }
}

Then, in my controller class (CentreController) I have these lines:

public async Task<JsonResult> Get(int Id)
{
  var centre = new Centre {CentreId = Id};
  // This is a call to our data service, which basically loads the centre object
  // from the database via Entity Framework.
  centre = (await CentreService.Get(centre)).Data;

  //centre.Location = null;
  //var jc = JsonConvert.SerializeObject(centre);

  return Json(centre,JsonRequestBehavior.AllowGet);
}

This gives me a 500 error and an exception about Null values.

If I uncomment the line

//centre.Location = null;

then the code runs fine, but no Location is transferred back to the caller.

If I uncomment the line

//var jc = JsonConvert.SerializeObject(centre);

Then my DbGeographyConverter is invoked, and the jc object contains the correct data that I want to return, but in a string instead of a JsonResult. The call to Json doesn't invoke the DbGeographyConverter and I can't work out why.

How can I get the Json call to run my custom converter? Or alternatively, how can I get my controller method to convert the output of JsonConvert to a JsonResult?


回答1:


You can convert to json using Json.NET and then return converted string using Content method. remember to add appropriate content type.

public async Task<ActionResult> Get(int Id)
{
    var centre = new Centre {CentreId = Id};
    centre = (await CentreService.Get(centre)).Data;

    var jc = JsonConvert.SerializeObject(centre);

    Response.ContentType = "application/json";
    return Content(jc)
}

Is it work for you?




回答2:


Use Json.NET nuget package, the default System.Web.Mvc.Json method can't handle the nullvalues from DbGeography.



来源:https://stackoverflow.com/questions/25196414/serializing-a-dbgeography-type-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!