0

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?

dylanT
  • 1,080
  • 1
  • 13
  • 26
  • The reason your converter doesn't get called when you use the controller's `Json` method is because MVC doesn't use Json.Net by default. You can either do what @py3r3str suggested or implement your own JsonNetResult to handle this. See [this question](http://stackoverflow.com/q/14591750/10263). – Brian Rogers Aug 08 '14 at 15:05

2 Answers2

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?

py3r3str
  • 1,879
  • 18
  • 23
0

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

juFo
  • 17,849
  • 10
  • 105
  • 142