简体   繁体   English

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

[英]Deserializing malformed json string

I'm trying to use JsonConvert to deserialize a string into an object, but I'm getting the exception: 我正在尝试使用JsonConvert将字符串反序列化为对象,但出现异常:

Unexpected character encountered while parsing value: s. 解析值s时遇到意外字符。 Path 'type.id', line 1, position 12. 路径“ type.id”,第1行,位置12。

This is happening because the input string is not a properly formed json string, I understand that. 发生这种情况是因为输入字符串不是格式正确的json字符串,据我所知。 However, the problem is that the string will never be a properly formatted json string and I cannot change that , but nonetheless, I still need to deserialize it to an object. 但是, 问题在于该字符串永远不会是格式正确的json字符串,并且我无法更改它 ,但是尽管如此,我仍然需要将其反序列化为一个对象。

The string: 字符串:

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

How can I convert this string to properly formatted json string so it can be deserialized to an object using JsonConvert? 如何将这个字符串转换为格式正确的json字符串,以便可以使用JsonConvert将其反序列化为对象?

If you can't go back to your datasource and fix it there, you can try to fix your JSON string. 如果无法返回到数据源并在那里进行修复,则可以尝试修复JSON字符串。

If it stays this simple, like in your sample you can select every word and wrap it in quotation marks: 如果它保持这种简单,就像您的示例中一样,您可以选择每个单词并将其用引号引起来:

//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);

Example: http://share.linqpad.net/sartkg.linq 示例: http//share.linqpad.net/sartkg.linq

Edit: fixed single quotes to double quotes. 编辑:将单引号固定为双引号。

I'd use Regex.Replace , like this: 我将使用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 = ...

If feels good to use regex though, https://xkcd.com/208/ :) 如果仍然可以使用正则表达式, 请https://xkcd.com/208/ :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM