public static ParseResult <JNumber> ParseFirstNumber(Substring encoded) { int i = LeadingWhiteSpaceCount(encoded); int numberStart = i; if (encoded[i] == '-') { i++; } else if (!IsDigit(encoded[i])) { throw new System.ArgumentException("No number found!"); } bool inFraction = false; bool inExponent = false; bool digitRead = false; bool fractionDigitRead = false; bool exponentDigitRead = false; while (i < encoded.Length) { char c = encoded[i]; if (IsDigit(c)) { i++; digitRead = true; if (inFraction) { fractionDigitRead = true; } if (inExponent) { exponentDigitRead = true; } continue; } else if (!inExponent && !inFraction && digitRead && c == '.') { inFraction = true; } else if (c == 'E' || c == 'e') { inFraction = false; inExponent = true; } else if (inExponent && !exponentDigitRead && (c == '+' | c == '-')) { i++; continue; } else { // We read something other than a valid character for a number break; } i++; } if (!digitRead) { throw new System.ArgumentException("No digits found! " + encoded.ToString()); } if (inFraction && !fractionDigitRead) { throw new System.ArgumentException("Fraction not terminated " + encoded.ToString()); } if (inExponent && !exponentDigitRead) { throw new System.ArgumentException("Exponent not terminated " + encoded.ToString()); } JNumber token = null; string numberAsString = encoded.SubSubstring(numberStart, i - numberStart).ToString(); if (fractionDigitRead || exponentDigitRead) { float result; var style = System.Globalization.NumberStyles.Float; var culture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US"); if (!float.TryParse(numberAsString, style, culture, out result)) { throw new System.ArgumentException("Unable to parse number from JSON: " + encoded.ToString()); } token = new JNumber(result); } else { int result; if (!int.TryParse(numberAsString, out result)) { throw new System.ArgumentException("Unable to parse number from JSON: " + encoded.ToString()); } token = new JNumber(result); } return(new ParseResult <JNumber> { Token = token, SubstringLength = i }); }
public void Set(string key, int number) { this[key] = new JNumber(number); }