Previously I wrote about several “gotchas” in the new JSON serializer that is built in to .NET Core 3.0. Another one has cropped up, but it is different enough that I thought it warranted its own post.
Type Promiscuity
Back in 2010 or something like that, Ted Neward gave a talk about JavaScript that changed my professional life forever… and it was just a “here’s some stuff about JavaScript” talk. Included in that talk was the now-ubiquitous “JavaScript is to Java like Hamburger is to Ham” (I don’t know if Ted invented it, but young me really thought it was funny), and the idea that JavaScript is type promiscuous. I’ve talked about this before, but essentially because JavaScript isn’t a strongly-typed language, it can freely flip a variable from representing a number to suddenly representing a string.
TypeScript helps combat this a little bit by providing type definitions at design and compile time, but during runtime it just reverts to JavaScript, and all bets are off.
In the above example, we have a variable that is defined as a number, but since it is bound via ngModel to this input control, it will end up be a string.
JSON
In JSON, strings are represented like you’d expect, with quotation marks, and numbers are represented without. That means you could be uploading an object to your WebAPI that has the wrong typed properties:
JSON.NET would handle this situation, but the new JSON Serializer does not – it just ignores that property, causing the deserialization to fail.
Fix
Since you have to handle this on the client side (aka the JavaScript side), you need to force your variables to be the correct type.
In our previous example, you can explicitly define the input control to be type=”number”, which preserves the typing. (Note, though, if you have a string variable and accidentally put type=”number” on your input control, it will still come back as a number!)
You can also force JavaScript to treat it as a number using the Number() function:
JavaScript is … special. And so I guess its expected that you might have to do some finagling when it comes to making sure that the variable types are correct.