反序列化格式错误的 json 字符串

Deserializing malformed json string

我正在尝试使用 JsonConvert 将字符串反序列化为对象,但出现异常:

Unexpected character encountered while parsing value: s. Path 'type.id', line 1, position 12.

发生这种情况是因为输入字符串的格式不正确 json,我明白这一点。但是,问题是该字符串永远不会是格式正确的 json 字符串,我无法更改它,但尽管如此,我仍然需要将其反序列化为一个对象。

字符串:

"{type: {id: schoolType1516,req: true,edit: yes},name: {id: schoolName1516,req: true,edit: yes}}"

如何将此字符串转换为格式正确的 json 字符串,以便使用 JsonConvert 将其反序列化为对象?

如果您无法返回到您的数据源并在那里修复它,您可以尝试修复您的 JSON 字符串。

如果它保持这么简单,就像在您的示例中一样,您可以 select 每个单词并将其用引号引起来:

//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+)";
// \"\" becomes "" which is the sequence for replace the first group (ie the one
// we caught above) with the same group but with extra "
var replacement = "\"\"";
var correctJSON = Regex.Replace(faultyJSON, match, replacement);
// Parse it.
var obj = ...

如果感觉使用正则表达式很好,https://xkcd.com/208/ :)