1

I have an issue serializing a JSON string to a key/value dictionary. The code is like:

var parameters = "{\"id\":123}";
JsonConvert.DeserializeObject<Dictionary<string, string>>(parameters);

This example seems work perfectly, giving me {[id,123]}.

Now. When I change the number to something like '070809' I suddenly get an exception: "Newtonsoft.Json.JsonReaderException: Input string '070809' is not a valid number. Path 'id', line 1, position 12. ---> System.FormatException: Additional non-parsable characters are at the end of the string."

var parameters = "{\"id\":070809}";
JsonConvert.DeserializeObject<Dictionary<string, string>>(parameters);

Any suggestions?

Bas Slagter
  • 9,831
  • 7
  • 47
  • 78
  • I appreciate that it doesn't solve your problem, but I found [this issue](https://github.com/JamesNK/Newtonsoft.Json/issues/924) which suggests it's by design. – ProgrammingLlama Jul 24 '18 at 07:10
  • Thanks @john. A leading zero doesn't seem to be the problem since '010203' as a value works as well. – Bas Slagter Jul 24 '18 at 07:12
  • 1
    There is something with the leading zero...'170809' does work. Doesn't explain why '010203' is working though – Bas Slagter Jul 24 '18 at 07:16

1 Answers1

6

Your second example isn't valid JSON. Recall that JSON is based on JavaScript, and in that language any numeric literal that starts with a 0 is interpreted as an octal number. Valid octal digits are 0-7, so if the literal contains an 8 or 9 then it cannot be parsed and will raise an error. ('010203' works because it is a valid octal literal but '070809' is not)

Bradley Smith
  • 13,353
  • 4
  • 44
  • 57
  • Okay...that explains a lot. But now the question. How to fix :D I do not want this code to blow up when someone accidentally enters an id like that. – Bas Slagter Jul 24 '18 at 07:18
  • The problem is with the input, not the deserialization. All you need to do is ensure that you are given valid JSON in the first place. – Bradley Smith Jul 24 '18 at 07:20