Newtonsoft Json.NET is a super popular (#1 most downloaded NuGet package) framework for serializing and deserializing json. In my experience, I haven’t really had to do much other than use the most basic serialization and deserialization.
Sometimes, though, there is a time when the API you’re working with presents you with something goofy. In my case, I was working with Yext, which is a service that can take business location information and publish it to a variety of places for you (such as Google, Yahoo, Yelp, etc).
Yext has the ability to store all kinds of information, including “custom fields,” which are defined by the user. There are different types of fields that you can create (text, date, etc), but all of them are designated with a special identification number. Unfortunately for the ease of deserialization, this identification number is, well, a number. That means you can’t just create a POCO with a field to match – because you can’t start a variable name with a numeral.
JsonConverter
The JsonConverter class lets you define how the serializer and deserializer does its job. This allows you to read in the json and put it into a C# structure that is easier to work with (say, a Dictionary<string, string>), and take the Dictionary<string, string> structure and serialize it back into json in the proper format.
JsonProperty
There is an easier way to get around this problem for this specific use case (Json keys starting with numbers), and that is the JsonProperty attribute. It’s pretty straightforward to use:
This way wasn’t ideal for my use, though, because the custom field identifiers can change in Yext depending on if you’re using their sandbox server vs. production, so, I needed to make things a little more fluid.