IC Improve Code Recipes

Chapter 12

XML and JSON

Every business system I have worked on moves data in and out as text. In the early years it was XML: SOAP envelopes, configuration files, nightly feeds from a bank, purchase orders from a trading partner. Later it was JSON: REST APIs, front-end payloads, message queues. Most systems I see today do both, often in the same process, because the partner who sent XML in 2008 still sends XML.

Serialization is one of the recurring themes in my consulting archive. Classes named for XML, JSON or serialization work turned up in 25 engagements, 3,732 of them in total. Most were thin wrappers: an XmlHelper with a Serialize and a Deserialize method, a JsonUtil that called a library with slightly different settings than the last one. The wrappers were not the problem. The settings inside them were. One wrapper built a new XmlSerializer with a custom root on every call and leaked memory until the app pool recycled. Another loaded partner XML with DTD processing on. A third serialized enums as numbers, and a reordered enum quietly corrupted a year of stored data.

This chapter gives you one well-configured way to do each job. You get System.Text.Json options set up once, source-generated serialization for hot paths, an XmlSerializer helper that does not leak, LINQ to XML recipes for the documents you don't want classes for, a converter between XML and JSON, and streaming readers for files too big to load. Everything here uses the base class library. No NuGet packages are required.

Recipes

  1. 12.1System.Text.Json Options Done OnceYou serialize and deserialize JSON in a dozen places. Each call site passes its own options, or no options at all, so one endpoint writes…
  2. 12.2Source-Generated SerializationReflection-based serialization is fast once warmed up, but the first call for each type pays to build its metadata. In a serverless function, a…
  3. 12.3XmlSerializer Without the LeaksA trading partner sends invoices as XML, and you would rather work with a class than with nodes. XmlSerializer does that job well, but it has a few…
  4. 12.4LINQ to XML for Documents Without ClassesNot every XML document deserves a class. You need three values from a configuration file, a quick transformation of a partner feed, or a small…
  5. 12.5Converting Between XML and JSONA legacy service returns XML and the new front end wants JSON. Or the reverse: a modern API posts JSON that must be forwarded to a mainframe gateway…
  6. 12.6Streaming Huge XML and JSON FilesA nightly feed arrives as a 3 GB XML file with two million <Transaction> elements, or as a JSON array of the same size. Loading it with…

Chapter checklist

  • Search for new JsonSerializerOptions inside methods. Replace them with one shared, read-only instance such as JsonDefaults.Web.
  • Serialize enums as strings in anything you store or send to a partner.
  • Use a JsonSerializerContext for cold-start-sensitive hosts, trimmed builds and profiled hot paths.
  • Find every new XmlSerializer( that passes an XmlRootAttribute or extra types, and move it behind a cache.
  • Read untrusted XML through an XmlReader with DtdProcessing.Prohibit and no resolver.
  • Replace string-built XML with XElement construction, and read values with nullable casts.
  • Name the elements that are always arrays when you convert XML to JSON.
  • Stream any file that can grow past a few hundred megabytes, and test that the reader does not skip records.