[英]Deserializing malformed json string
我正在尝试使用JsonConvert将字符串反序列化为对象,但出现异常:
解析值s时遇到意外字符。 路径“ type.id”,第1行,位置12。
发生这种情况是因为输入字符串不是格式正确的json字符串,据我所知。 但是, 问题在于该字符串永远不会是格式正确的json字符串,并且我无法更改它 ,但是尽管如此,我仍然需要将其反序列化为一个对象。
字符串:
"{type: {id: schoolType1516,req: true,edit: yes},name: {id: schoolName1516,req: true,edit: yes}}"
如何将这个字符串转换为格式正确的json字符串,以便可以使用JsonConvert将其反序列化为对象?
如果无法返回到数据源并在那里进行修复,则可以尝试修复JSON字符串。
如果它保持这种简单,就像您的示例中一样,您可以选择每个单词并将其用引号引起来:
//we only need every match once
var matches = Regex.Matches(source, @"\w+")
.OfType<Match>()
.Select (m => m.Groups[0].Value)
.Distinct();
foreach (var match in matches)
{
source = source.Replace(match, String.Format("\"{0}\"", match));
}
JObject obj = JObject.Parse(source);
示例: http : //share.linqpad.net/sartkg.linq
编辑:将单引号固定为双引号。
我将使用Regex.Replace
,如下所示:
// Exchange all words with words surrounded by `"`
// ((\\w+\\s+)*\\w+) becomes ((\w+\s+)*\w+), ie all words with possible spaces
var match = "((\\w+\\s+)*\\w+)";
// \"$1\" becomes "$1" which is the sequence for replace the first group (ie the one
// we caught above) with the same group but with extra "
var replacement = "\"$1\"";
var correctJSON = Regex.Replace(faultyJSON, match, replacement);
// Parse it.
var obj = ...
如果仍然可以使用正则表达式, 请https://xkcd.com/208/ :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.