简短的回答:首先您需要反序列化转义的字符串,但不是目标 CLR 类型,而是反序列化为另一个字符串(必要时重复);然后,将其反序列化为目标类型:
// Initial example json string: "\"{\\\"Property1\\\":1988,\\\"Property2\\\":\\\"Some data :D\\\"}\""
// First, deserialize to another string (unescaped string).
string unescapedJsonString = JsonConvert.DeserializeObject<string>(escapedJsonString);
Debug.WriteLine(unescapedJsonString);
// Prints:
// "{\"Property1\":1988,\"Property2\":\"Some data :D\"}"
// Second, deserialize to another string, again (in this case is necessary)
var finalUnescapedJsonString = JsonConvert.DeserializeObject<string>(unescapedJsonString);
Debug.WriteLine(finalUnescapedJsonString);
// This time prints a final, unescaped, json string:
// {"Property1":1988,"Property2":"Some data :D"}
// Finally, perform final deserialization to the target type, using the last unescaped string.
MyClass targetObject = JsonConvert.DeserializeObject<MyClass>(finalUnescapedJsonString);
长答案(但有趣)
使用string.Replace(...
可能会生成无效字符串,因为它可能会损坏某些需要反斜杠正确反序列化的特殊字符。
这种类型的转义字符串通常是在已经是 json 字符串的字符串再次序列化(甚至更多次)时生成的。这会导致类似“各种级别的序列化”(它实际上是带有保留字符的字符串的序列化),结果是反斜杠字符(或后面的一个、两个或多个反斜杠组:\、\、\\\)散落在弦上。因此,正确删除它们并不足以将它们替换为空。
正确的方法:获得非转义字符串的更好方法是对字符串类型进行第一次反序列化(如有必要,重复几次),然后对目标 CLR 类型进行最终反序列化:
// -- SERIALIZATION --
// Initial object
MyClass originObj = new MyClass { Property1 = 1988, Property2 = "Some data :D" };
// "First level" Of serialization.
string jsonString = JsonConvert.SerializeObject(originObj);
Debug.WriteLine(jsonString);
// Prints:
// {"Property1":1988,"Property2":"Some data :D"}
// "Second level" of serialization.
string escapedJsonString = JsonConvert.SerializeObject(jsonString);
Debug.WriteLine(escapedJsonString);
// "{\"Property1\":1988,\"Property2\":\"Some data :D\"}"
// Note the initial and final " character and de backslash characters
// ...
// at this point you could do more serializations ("More levels"), Obtaining as a result more and more backslash followed,
// something like this:
// "\"{\\\"Property1\\\":1988,\\\"Property2\\\":\\\"Some data :D\\\"}\""
// Note that is... very very crazy :D
// ...
// -- DESERIALIZATION --
// First deserialize to another string (unescaped string).
string unescapedJsonString = JsonConvert.DeserializeObject<string>(escapedJsonString);
Debug.WriteLine(unescapedJsonString);
// Prints:
// {"Property1":1988,"Property2":"Some data :D"}
// ...
// at this point you could repeat more deserializations to string, if necessary. For example if you have many backslash \\\
// ...
// Finally, perform final deserialization to the target type, using the last unescaped string.
MyClass targetObject = JsonConvert.DeserializeObject<MyClass>(unescapedJsonString);