Menu

1 / 2

Obfuscating a type you serialize with Newtonsoft.Json: [JsonProperty] is the contract, and TypeNameHandling''s $type is a landmine

DEV Community: dotnet·Zero Heartbeat·about 15 hours ago
#nhqFP8AP
#devtodotnet#devto#dev#type#json
Reading 0:00
15s threshold

Here is a type that works perfectly until the day you obfuscate it:

public sealed class Order { public string Customer { get ; set ; } = "" ; public decimal Total { get ; set ; } public DateTime PlacedOn { get ; set ; } }

Enter fullscreen mode

Exit fullscreen mode

Serialize it with JsonConvert.SerializeObject(order) and you get {"Customer":"…","Total":…,"PlacedOn":"…"} . Run the assembly through a renamer and serialize again, and you get {"a":"…","b":…,"c":"…"} . Nothing threw. The build was green. Every consumer of that JSON — a frontend, a sister service, a document you stored last week and read back today — is now broken, and it broke at runtime, in a place no compiler and no build step could ever see.

This is the single most common way obfuscation "breaks serialization," and with Newtonsoft.Json it bites harder than with System.Text.Json , for one structural reason: Json.NET has no compile-time source generator .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.