David Pfeffer
David Pfeffer

Reputation: 39823

Change JSON.NET serialization for a particular type (not mine)

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!

Upvotes: 3

Views: 2009

Answers (1)

Stuart
Stuart

Reputation: 66882

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:

  • CanConvert - should this converter be used on this member
  • WriteJson - handles the object to string output
  • ReadJson - handles the string to object parsing

The converters themselves are registered with JSON.Net using JsonSerializerSettings - e.g:

new JsonSerializerSettings
                   {
                       MissingMemberHandling = MissingMemberHandling.Ignore,
                       NullValueHandling = NullValueHandling.Ignore,
                       DefaultValueHandling = DefaultValueHandling.Include,
                       ContractResolver = new JsonConventionResolver(),
                       Converters = new List<JsonConverter>
                                        {
                                            new TwitterDateTimeConverter(),
                                            new TwitterWonkyBooleanConverter(),
                                            new TwitterGeoConverter()
                                        }
                   })

(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.

Upvotes: 7

Related Questions