我有一些JSON解析,看起来像这样:
{
"dhkplhfnhceodhffomolpfigojocbpcb": {
"external_crx": "C:Program FilesBabylonBabylon-ProUtilsBabylonChrome.crx",
"external_version": "1.1"
}
}
不幸的是,JSON。. NET确实给了我一个错误,因为单个斜杠。是否有一种方法允许单斜杠?如果不是,我可以使用什么Regex以安全的方式对文件路径进行双斜杠处理,而不会弄乱其他可能具有正确双斜杠的条目?
更新错误(使用JsonTextReader)是"坏的JSON转义序列: p。4号线,25号位置。"事实证明,在这个问题上还有更多的问题需要解决,因为反斜杠是用来支持十六进制和八进制值的(http://json.codeplex.com/discussions/244265)。我怎么知道,当我看到一个十六进制/八进制,而不仅仅是一个文件路径反斜杠,有人忘记了双反斜杠?
case 'u':
// ...
case 'x':
hexValues = new char[2];
for (int i = 0; i < hexValues.Length; i++)
{
if ((currentChar = MoveNext()) != ' ' || !_end)
hexValues[i] = currentChar;
else
throw CreateJsonReaderException("Unexpected end while parsing unicode character. Line {0}, position {1}.", _currentLineNumber, _currentLinePosition);
}
hexChar = Convert.ToChar(int.Parse(new string(hexValues), NumberStyles.HexNumber, NumberFormatInfo.InvariantInfo));
_buffer.Append(hexChar);
break;
default:
var octValues = new char[3];
var octLength = 0;
for (int i = 0; i < octValues.Length; i++)
{
var octalChar = i==0 ? currentChar : PeekNext();
if ((octalChar > 1 || !_end) && octalChar>='0' && octalChar<'8')
{
octValues[i] = (char)octalChar;
if(i!=0) MoveNext();
octLength++;
}
else
{
break;
}
}
if (octLength>0)
{
hexChar = Convert.ToChar(Convert.ToInt32(new string(octValues, 0, octLength), 8));
_buffer.Append(hexChar);
break;
}
throw CreateJsonReaderException("Bad JSON escape sequence: {0}. Line {1}, position {2}.", @"" + currentChar, _currentLineNumber, _currentLinePosition);
}
}
else
{
throw CreateJsonReaderException("Unterminated string. Expected delimiter: {0}. Line {1}, position {2}.", quote, _currentLineNumber, _currentLinePosition);
}
break;
如果要用双反斜杠替换单反斜杠,但保留现有的双斜杠,请搜索
(?<!\)\(?!\)
将替换为
\\
对于c#, RegexBuddy创建以下代码片段:
resultString = Regex.Replace(subjectString,
@"(?<!\) # lookbehind: Check that previous character isn't a
\ # match a
(?!\) # lookahead: Check that the following character isn't a ",
@"\", RegexOptions.IgnorePatternWhitespace);
错误是什么?你的deserializeObject是什么?
如果你使用这样的语句:
data = JsonConvert.DeserializeObject<Dictionary<Object, Object>>(jsonText);
你应该不会有任何问题。