Deserialize hexadecimal values with Newtonsoft JSON

Viewed 958

I'm trying to deserialize json into a C# object. The json basically looks like this:

{ "hexValue": "0x9a7f" }

My POCO looks like this:

public class HexTest
{
     public int hexValue;
}

I've read in a link from this question that Newtonsoft supports deserializing hex values. But in all fairness, those release notes were published a decade ago. I've even read in some source code on github published here what appears to be code to deserialize a hex formatted string that starts with "0x". Yet, when I try to deserialize a hex value, I always get the following exception:

Could not convert string to int: 0x9a7f.

It doesn't matter what type I try. I've tried using int long decimal Decimal, etc... From reading the source it looked like the Decimal type should have worked but nothing works. Does Newtonsoft really have support for converting hex values defined as strings into a numeric data type of some kind?

Sure, I know I can use the information in the question I linked to above to implement custom support for it but I'd really rather use the built-in support if it's there.

1 Answers

Thanks to the comments to my original question above by Fildor, I was able to resolve the problem by removing quotes around the value in the JSON so it now read like this:

{ "hexValue": 0x9a7f }

Also, further testing reveals that any of the numeric data types work for this in the POCO including int, long, and decimal. It is probably worth noting that (not sure about the latest standard) most if not all JSON validators will consider this invalid JSON because hexadecimal is not a valid JSON numeric data type.

Taking another look at the source, it's clear why this works and not the string. The parser will only call the method that detects the 0x prefix if it recognizes the json value token as a numeric type which, if quoted, it cannot do because by definition, that is a string.

Related