System.Text.Json does not serialize properties with private setters unless marked. ✔ Fix: [JsonInclude] public string Name { get; private set; } 💡 Hidden Trick This works even when constructor injection is used — extremely useful for DDD entities.
Tag: json
.NET Core JSON Serializer Pitfalls — Why Your Properties Don’t Serialize
System.Text.Json is fast……but very strict. Common Pain Points Missing getters Private setters PascalCase vs camelCase mismatch Ignored fields without [JsonInclude] Cycles now break serialization ✔ Life-Saving Fix Add: options.PropertyNameCaseInsensitive = true; options.ReferenceHandler = ReferenceHandler.IgnoreCycles; ✔ Hidden Trick For private setters: [JsonInclude] public string Name { get; private set; } This is rarely mentioned but solves […]
How to get formatted JSON in C#
Like converting XML to Json or Json to XML, you can also use Newtonsoft to get formatted Json. private static string FormatJson(string json) { dynamic parsedJson = JsonConvert.DeserializeObject(json); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } Note: You can use var instead of dynamic. Both will work.
How to convert JSON to XML or XML to JSON in C#
To do that easily, you can use Newtonsoft. // To convert an XML node contained in string xml into a JSON string XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); string jsonText = JsonConvert.SerializeXmlNode(doc); // To convert JSON text contained in string json into an XML node XmlDocument doc = JsonConvert.DeserializeXmlNode(json); You can get more info from […]

