Beispiel #1
0
        static bool StartsWithKeyword(string text)
        {
            int p;

            if (text.StartsWith("true") || text.StartsWith("null"))
            {
                p = 4;
            }
            else if (text.StartsWith("false"))
            {
                p = 5;
            }
            else
            {
                return(false);
            }
            while (p < text.Length && BaseReader.IsWhite(text[p]))
            {
                p++;
            }
            if (p == text.Length)
            {
                return(true);
            }
            char ch = text[p];

            return(ch == ',' || ch == '}' || ch == ']' || ch == '#' || ch == '/' && (text.Length > p + 1 && (text[p + 1] == '/' || text[p + 1] == '*')));
        }
Beispiel #2
0
        void WriteString(string value, TextWriter tw, int level, bool hasComment, string separator)
        {
            if (value == "")
            {
                tw.Write(separator + "\"\""); return;
            }

            char left = value[0], right = value[value.Length - 1];
            char left1 = value.Length > 1 ? value[1] : '\0', left2 = value.Length > 2 ? value[2] : '\0';
            bool doEscape = hasComment || value.Any(c => NeedsQuotes(c));

            if (doEscape ||
                BaseReader.IsWhite(left) || BaseReader.IsWhite(right) ||
                left == '"' ||
                left == '\'' ||
                left == '#' ||
                left == '/' && (left1 == '*' || left1 == '/') ||
                HjsonValue.IsPunctuatorChar(left) ||
                HjsonReader.TryParseNumericLiteral(value, true, out JsonValue dummy) ||
                StartsWithKeyword(value))
            {
                // If the string contains no control characters, no quote characters, and no
                // backslash characters, then we can safely slap some quotes around it.
                // Otherwise we first check if the string can be expressed in multiline
                // format or we must replace the offending characters with safe escape
                // sequences.

                if (!value.Any(c => NeedsEscape(c)))
                {
                    tw.Write(separator + "\"" + value + "\"");
                }
                else if (!value.Any(c => NeedsEscapeML(c)) && !value.Contains("'''") && !value.All(c => BaseReader.IsWhite(c)))
                {
                    WriteMLString(value, tw, level, separator);
                }
                else
                {
                    tw.Write(separator + "\"" + JsonWriter.EscapeString(value) + "\"");
                }
            }
            else
            {
                tw.Write(separator + value);
            }
        }