tips for deserializing json using newtonsoft.json

in #technologylast year

I just want to share a few tips when deseralizating json strings using the newtonsoft.json library.

  • setup a root object that contains all objects on the server side

This is mainly a stylistic choice, but well from my own experience feeding a json array (e.g something like [ "object1":{} ]) can confuse the deseralization process.

  • it might be best to make use of the JsonProperty attribute

This is because in its default settings it looks for public properties whose name is a 1:1 match.

In essence if the json has a property named _locationdescthe csharp class which it will be deserialized into must also have public string _locationdesc { get; set; }.

This issue however can be fixed if you make use of the JsonProperty attribute in this way [JsonProperty("_locationdesc")]

Just wanted to share this because its something I kept forgetting and had to relearn through debugging and experimentation.