在MVC中序列化DbGeography类型 [英] Serializing a DbGeography type in MVC

查看:81
本文介绍了在MVC中序列化DbGeography类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

序列化DbGeography类型时遇到问题.我的控制器操作总是给出错误而不是对象.

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

我的DbGeographyConverter类的定义如下:

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

然后,在我的控制器类(CentreController)中,这些行如下:

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

这给了我500错误和一个有关Null值的异常.

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

如果我取消注释行

//centre.Location = null;

然后代码可以正常运行,但不会将位置转移回调用方.

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

如果我取消注释行

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

然后调用我的DbGeographyConverter,并且jc对象包含我要返回的正确数据,但使用字符串而不是JsonResult.调用Json不会调用DbGeographyConverter,我也无法弄清楚为什么.

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.

如何获得Json调用以运行我的自定义转换器?或者,如何获取控制器方法以将JsonConvert的输出转换为JsonResult?

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?

推荐答案

您可以使用Json.NET转换为json,然后使用Content方法返回转换后的字符串.记得添加适当的内容类型.

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

对您有用吗?

这篇关于在MVC中序列化DbGeography类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆