I am using Newtonsoft’s JSON.NET library to serialize some objects. In particular, I want to store NetTopologySuite Point classes (or GeoAPI IPoint interfaces) as properties on my objects.
I only want to store a latitude and longitude property in my resulting JSON. In contrast, IPoint has X, Y, Z, and several other properties.
Can I somehow inject my own logic for how to serialize/deserialize this particular type to/from JSON?
Thanks!
For this sort of operation, I always look at TweetSharp and how it handles it.
For example, TweetSharp uses a TwitterGeoConverter.cs to serialise/deserialise the TwitterGeoLocation.GeoCoordinates type to/from JSON:
https://github.com/danielcrenna/tweetsharp/blob/master/src/net40/TweetSharp.Next/Serialization/Converters/TwitterGeoConverter.cs
The key methods in this converter are:
The converters themselves are registered with JSON.Net using JsonSerializerSettings – e.g:
(from https://github.com/danielcrenna/tweetsharp/blob/master/src/net40/TweetSharp.Next/Serialization/SerializerBase.cs)
Alternatively, you can also register converters using attributes – see https://github.com/geersch/JsonNetDateTimeConverter
Or… if the case is very simple and if you own the source code – then if you simply want to ignore some properties during the serialisation, then there is a
[JsonIgnore]attribute available for the properties you want to skip.