简体   繁体   中英

Deserializing malformed json string

I'm trying to use JsonConvert to deserialize a string into an object, but I'm getting the exception:

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

This is happening because the input string is not a properly formed json string, I understand that. 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.

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?

If you can't go back to your datasource and fix it there, you can try to fix your JSON string.

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

Edit: fixed single quotes to double quotes.

I'd use Regex.Replace , like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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