Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

c# - Override Json deserializing a number with a leading zero as a decimal and not an octal value

I am generating a json object,

{
   "number":0100
}

When this object is deserialized in C# using Newtonsoft.Json, 0100 is treated as an octal number because of the leading zero. Is there a way to override this functionality and make it consider the number as a decimal integer?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If Newtonsoft.Json does that, then it is a bug. According to the JSON syntax as documented on http://json.org:

"A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used."

and the syntax graph does not allow a number to have a leading non-significant zero.

RFC 4627 Section 2.4. agrees:

"Octal and hex forms are not allowed. Leading zeros are not allowed."

So in fact, your use of leading zeros is not valid JSON at all ... according to the RFC.


So, to answer your question:

Is there a way to override this functionality and make it consider the number as a decimal integer?

Probably not. Moreover, you shouldn't do it. Instead you should fix the JSON, or complain to the people who are generating it that it is not conformant.

You should also report this as a bug in Newtonsoft.Json.. Don't bother. The author does not acknowledge this as a bug. I would advise switching to a JSON library that implements the JSON spec correctly.


ADVICE FOR JSON IMPLEMENTERS

The JSON specs (both version) clearly say that hexadecimal and octal forms are not allowed.

If you add support for hex and/or octal (or some other unofficial "extension") to your JSON parser, you are adding to the fragmentation of the JSON standard. This is bad.

It is also a bad idea because many end-users are surprised when a non-significant leading zero is treated as an octal marker. This leads to Questions like this ... where (I'm guessing) the OP's end-users have been burned, and are requesting him to fix >>his<< code to handle leading zeros "properly".

The correct behavior here is to strictly implement the JSON spec, and reject any number with a non-significant leading zero. (Personally, I'd implement special-case error messages for this and for "0x..." hexadecimal forms.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...