我陷入了一个不可能的境地。我有来自外太空的JSON数据(他们绝对不会改变它)。以下是JSON数据:
{
user:'180111',
title:'I\'m sure "E pluribus unum" means \'Out of Many, One.\' \n\nhttp://en.wikipedia.org/wiki/E_pluribus_unum.\n\n\'',
date:'2007/01/10 19:48:38',
"id":"3322121",
"previd":112211,
"body":"\'You\' can \"read\" more here [url=http:\/\/en.wikipedia.org\/?search=E_pluribus_unum]E pluribus unum[\/url]'s. Cheers \\*/ :\/",
"from":"112221",
"username":"mikethunder",
"creationdate":"2007\/01\/10 14:04:49"
}
我说:“这根本不是有效的JSON。”他们回答道:“嗯!但JavaScript可以读取它而没有投诉。”
<html>
<script type="text/javascript">
var obj = {"PUT JSON FROM UP THERE HERE"};
document.write(obj.title);
document.write("<br />");
document.write(obj.creationdate + " " + obj.date);
document.write("<br />");
document.write(obj.body);
document.write("<br />");
</script>
<body>
</body>
</html>
问题
我需要通过.NET(4)读取和解析这个字符串,但它破坏了Json.org C#部分中提到的14个库中的3个(没有尝试其他库)。为了解决这个问题,我编写了以下函数来修复单引号和双引号的问题。
public static string JSONBeautify(string InStr){
bool inSingleQuote = false;
bool inDoubleQuote = false;
bool escaped = false;
StringBuilder sb = new StringBuilder(InStr);
sb = sb.Replace("`", "<°)))><"); // replace all instances of "grave accent" to "fish" so we can use that mark later.
// Hopefully there is no "fish" in our JSON
for (int i = 0; i < sb.Length; i++) {
switch (sb[i]) {
case '\\':
if (!escaped)
escaped = true;
else
escaped = false;
break;
case '\'':
if (!inSingleQuote && !inDoubleQuote) {
sb[i] = '"'; // Change opening single quote string markers to double qoute
inSingleQuote = true;
} else if (inSingleQuote && !escaped) {
sb[i] = '"'; // Change closing single quote string markers to double qoute
inSingleQuote = false;
} else if (escaped) {
escaped = false;
}
break;
case '"':
if (!inSingleQuote && !inDoubleQuote) {
inDoubleQuote = true; // This is a opening double quote string marker
} else if (inSingleQuote && !escaped) {
sb[i] = '`'; // Change unescaped double qoute to grave accent
} else if (inDoubleQuote && !escaped) {
inDoubleQuote = false; // This is a closing double quote string marker
} else if (escaped) {
escaped = false;
}
break;
default:
escaped = false;
break;
}
}
return sb.ToString()
.Replace("\\/", "/") // Remove all instances of escaped / (\/) .hopefully no smileys in string
.Replace("`", "\\\"") // Change all "grave accent"s to escaped double quote \"
.Replace("<°)))><", "`") // change all fishes back to "grave accent"
.Replace("\\'","'"); // change all escaped single quotes to just single quote
}
现在JSONlint只会抱怨属性名称,我可以使用JSON.NET和SimpleJSON库来解析上述JSON。
问题:我确信我的代码不是修复上述JSON的最佳方式。是否存在任何可能导致我的代码出错的情况?有更好的方法吗?