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?