Search code examples
c#json.netjson-deserializationleading-zero

How to deal with leading zeroes while deserialising a JSON request?


I have this piece of source code, used for deserialising a JSON request:

dynamic obj = JsonConvert.DeserializeObject(telegram.ReceiveTelegram);

When my JSON request looks as follows, there is no problem:

{"Task":{...,"PosX":2278,"PosY":6500,...}}

When it looks as follows, I have an Exception:

{"Task":{...,"PosX":02278,"PosY":06500,...}}

This is the mentioned Exception:

Newtonsoft.Json.JsonReaderException: Input string '02278' is not a valid number. Path 'State.PosX', line 1, position 385. ---> System.FormatException: Additional non-parsable characters are at the end of the string. at System.ParseNumbers.StringToLong(String s, Int32 radix, Int32 flags, Int32* currPos) at System.Convert.ToInt64(String value, Int32 fromBase) at Newtonsoft.Json.JsonTextReader.ParseReadNumber(ReadType readType, Char firstChar, Int32 initialPosition)

Apparently the deserialiser can't handle leading zeroes.

The target framework of my C# application is .NET Framework 4.6.1.

What can I do in order to solve this?

Thanks in advance


Solution

  • It's not valid JSON to have leading zeroes in a number that is not enclosed in quotes.

    See the offical spec, RFC8259:

    1. Numbers
      The representation of numbers is similar to that used in most programming languages. A number is represented in base 10 using decimal digits. It contains an integer component that may be prefixed with an optional minus sign, which may be followed by a fraction part and/or an exponent part. Leading zeros are not allowed.