3

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!

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

First link is a dead link (404) on GitHub. :-/
All the links are dead :(

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.