Can I make Json.net deserialize a C# 9 record type with the “primary” constructor, as if it had [JsonConstructor]?

Firstly, you only have to do this when you create your own constructors. This is due to the fact that on instantiation it won’t know which one to use. Secondly, note that (by default) the deserializer will use the property and constructor names and overwrite the ones you omit in the actual constructor type. Furthermore, … Read more

TypeNameHandling caution in Newtonsoft Json

When deserialize with TypeNameHandling.All and without a SerializationBinder checks json.net will try to create a instace of the type that comes as metadata in the JSON. public class Car { public string Maker { get; set; } public string Model { get; set; } } { “$type”: “Car”, “Maker”: “Ford”, “Model”: “Explorer” } //create a … Read more

Deserialize JSON to nested C# Classes

Your problem is twofold: You don’t have a class defined at the root level. The class structure needs to match the entire JSON, you can’t just deserialize from the middle. Whenever you have an object whose keys can change, you need to use a Dictionary<string, T>. A regular class won’t work for that; neither will … Read more

Using JSON to Serialize/Deserialize TimeSpan

I tried #Jessycormier’s method and it didn’t work for me. I ran DataContractJsonSerializer to see what it would generate and I found that gave me a value that looked more like this. {“PassedTimeSpan”:”P1DT2H3M4S”} The value shown above was for 1 day, 2 hours, 3 minutes, and 4 seconds. So it looks like format is: [-]P[{days}D][T[{hours}H][{min}M][{sec}S]] … Read more

Custom conversion of specific objects in JSON.NET

If anyone’s interested in my solution: When serializing certain collections, I wanted to create an associative json array instead of a standard json array, so my colleague client side developer can reach those fields efficiently, using their name (or key for that matter) instead of iterating through them. consider the following: public class ResponseContext { … Read more

What is the JSON.NET equivalent of XML’s XPath, SelectNodes, SelectSingleNode?

Json.NET has SelectToken. It uses a syntax similar to DataBinder.Eval to get JSON via a string expression: JObject o = JObject.Parse(“{‘People’:[{‘Name’:’Jeff’},{‘Name’:’Joe’}]}”); // get name token of first person and convert to a string string name = (string)o.SelectToken(“People[0].Name”); Or if you wanted to select multiple values: JObject o = JObject.Parse(“{‘People’:[{‘Name’:’Jeff’,’Roles’:[‘Manager’, ‘Admin’]}]}”); // get role array token … Read more