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

Order of Recursion (SQL Server CTE)

sql-server recursion common-table-expression with-statement

I can achieve recursion by using SQL Server's With command (CTE).

showSoftInput doesn't work after orientation change

android android-softkeyboard android-keypad android-input-method

I have a fragment with a single EditText that needs the soft keyboard to remain open continually. The keyboard gets hidden when the screen is rotated. I'm calling showSoftInput in OnActivityCreated