C# Json:如何使用 json.net 正确去除转义字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16331770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:46:08  来源:igfitidea点击:

Json: how to properly strip the escape characters with json.net

c#jsonstringjson.net

提问by Sharon C Lawrence

I have json response in the below format.

我有以下格式的 json 响应。

"[{\\"JobID\\":\\"1\\",\\"BillGenerationDate\\":\\"4/29/2013 2:53:34 PM\\",\\"BillID\\":\\"115743\\",\\"BillNo\\":\\"115743\\",\\"CustomerID\\":\\"4041705\\",\\"PayStatus\\":\\"0\\",\\"PaymentRequiredStatus\\":\\"True\\",\\"ProductName\\":\\"Epic FBO test\\",\\"Description\\":\\"Epic Automation 2\\r\\n\\",\\"ProductType\\":\\"eBill \\",\\"DueType\\":\\"-1\\",\\"DueDate\\":\\"2013-03-15\\",\\"Amount\\":\\"63.70\\",\\"Cost\\":\\"\\"},
{\\"JobID\\":\\"9\\",\\"BillGenerationDate\\":\\"5/2/2013 10:21:39 AM\\",\\"BillID\\":\\"115743\\",\\"BillNo\\":\\"115743\\",\\"CustomerID\\":\\"4041705\\",\\"PayStatus\\":\\"0\\",\\"PaymentRequiredStatus\\":\\"True\\",\\"ProductName\\":\\"FBO Test Product\\",\\"Description\\":\\"FBO Product Test\\",\\"ProductType\\":\\"eBill \\",\\"DueType\\":\\"-1\\",\\"DueDate\\":\\"2013-05-01\\",\\"Amount\\":\\"150.70\\",\\"Cost\\":\\"\\"}]

I believe json.net handles the escape characters and I used the below code to deserialize it to a dictionary collection.

我相信 json.net 处理转义字符,我使用以下代码将其反序列化为字典集合。

var billList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(contentCorrected);

But this json parsing throws exception "Invalid property identifier character: . Path '[0]', line 1, position 2." Could we solve this by manipulating the json response string?

但是这个json解析抛出异常“无效的属性标识符字符:路径'[0]',第1行,位置2。” 我们可以通过操作 json 响应字符串来解决这个问题吗?

采纳答案by Bijoy K Jose

Try string contentCorrected = contentCorrected.Replace(@"\", "");before deserialization process.

string contentCorrected = contentCorrected.Replace(@"\", "");在反序列化过程之前尝试。

回答by Murugan

  1. Remove all the "\" character before you deserialize it. Use replace function.

    yourJsonString.Replace("\\\\\", "");

  2. Your Json string is incomplete or doesnot seems to be of type List<Dictionary<string, string>>". Correct the type you want the json to be converted. I modified your json a little as follows and it worked.

    newJson = "{ \"array\":" + yourJsonString + "}"

  1. 在反序列化之前删除所有“\”字符。使用替换功能。

    yourJsonString.Replace("\\\\", "");

  2. 您的 Json 字符串不完整或似乎不是 类型List<Dictionary<string, string>>"。更正您希望转换 json 的类型。我对您的 json 进行了如下修改,它起作用了。

    newJson = "{ \"array\":" + yourJsonString + "}"

回答by Prabhat

For me the code below works

对我来说,下面的代码有效

string contentCorrected = contentCorrected.Replace(**@"\""", ""**);

回答by Jos R.

The problem occurs when valid double quotes are used within the answer. Removing and/or Replacing won't solved this in all cases. It frustrated me too until I found a simple solution:

在答案中使用有效的双引号时会出现问题。在所有情况下,删除和/或替换不会解决这个问题。它也让我感到沮丧,直到我找到了一个简单的解决方案:

var billList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(@contentCorrected);

回答by Johan Alzate

THE SHORT ANSWER:first you need to deserialize the escaped string, but not to the target CLR type, but deserialize to another string:

简短回答:首先您需要反序列化转义字符串,但不是反序列化到目标 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);

LONG ANSWER (but interesting)Using string.Replace(...could generate an invalid string, because it could damage certain special characters that needed the backslash to be deserialized correctly .

长答案(但很有趣)Usingstring.Replace(...可能会生成无效字符串,因为它可能会损坏某些需要正确反序列化反斜杠的特殊字符。

This type of escaped stringsare usually generated when a string that was already a json string, its serialized again (or even more times). This causes something like "various levels of serialization" (it really is a serialization of a string with reserved characters), and the result is backshash characters (or groups of one, two or more backslash followed: \, \\, \\\) scattered all over the string. So, to remove them correctly is not enough to replace them by empty.

这种类型的转义字符串通常是在一个已经是 json 字符串的字符串再次序列化(甚至更多次)时生成的。这会导致类似“各种级别的序列化”(它实际上是带有保留字符的字符串的序列化),结果是反斜杠字符(或一组、两个或多个反斜杠后跟:\、\\、\\\ ) 散落在整个弦上。因此,正确删除它们不足以用空替换它们。

THE RIGHT WAY:A better way to get a unescaped stringwould be to do a first deserialization to string type (Repeat this several times if necessary), And then do a final deserialization to target CLR type:

正确的方法获得未转义字符串的更好方法是对字符串类型进行第一次反序列化(如有必要,重复几次),然后对目标 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);