How to control JSON.NET serialization of System.Data.Spatial.DbGeometry

I have a DB First Entity Framework 5 Data Access Layer that is mapped to a table containing a SQL geometry type field called CenterCoordinate. The resulting entity contains this:

public System.Data.Spatial.DbGeometry CenterCoordinate { get; set; }

My client javascript requests the API and only accepts JSON. I then use the Web API to serve this using the default formatter (JSON.NET). In the API controller the field has a long list of properties including an XCoordinate and a YCoordinate.

In the client the JSON only contains this:

Geometry: Object CoordinateSystemId: 3498 WellKnownBinary: null WellKnownText: "POINT (6438089.715 1801515.828)"

I really don't want to have to parse out the WellKnownText to get to the values of X and Y.

So the question is how can I control the serialisation/de-serialisation of System.Data.Spatial types to/from JSON such that I get something more useful? How does the formatter know what to include/exclude?

Note: I really don't want decorate the entity with attributes as these will be lost each time I regenerate the model from the database (I have no idea why we can't add attributes to model fields through VS2012 and have it remember them after a regeneration). So can this be with partial classes or overriding the formatter?

Thanks, Matt


Unfortunately, you're more or less stuck parsing the WellKnownText field if you want to manipulate the coordinates with Javascript.

Geometry is a SQLSpatial type that is saved to a database via the WKT field, so that's why your DbGeometry type is converting the JSON to that format.

If it makes you feel any better, it's causing me just as much of a hassle right now.

Edit: These resources might help a bit:

GeoJSON has a structure much more similar to SpatialSQL:

This is a solution used to serialize/deserialize DbGeo types as JSON:

Need Your Help

Castle ActiveRecord something like RowState Property?

c# castle-activerecord

I was looking web for something like DataRow.RowState property in ActiveRecord class, but no luck. I simply want to know whether object has changed or not.

How can I use a UIScrollView to change values, just like a UISlider?

iphone iphone-sdk-3.0 uiscrollview ios4

So a UISlider works great to change/choose values but it just doesn't look that great. What i'd like to implement is more like a horizontally spinning dial. I already have all the graphics I need and

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.