JSON:如何正确地剥离转义字符json.net

gwo2fgha  于 2023-11-20  发布在  .NET
关注(0)|答案(5)|浏览(148)

我有下面格式的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\\\":\\\"\\\"}]

字符串
我相信json.net会处理转义字符,我使用下面的代码将其转换为字典集合。

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


但是这个json解析抛出异常“Invalid property identifier character:. Path '[0]',line 1,position 2.”我们可以通过操作json响应字符串来解决这个问题吗?

jhdbpxl9

jhdbpxl91#

**THE SHORT ANSWER:**首先需要将转义的字符串反编译为目标类型,但不是反编译为目标类型,而是反编译为另一个字符串(必要时重复);然后,它被反编译为目标类型:

// 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(但很有趣)**使用string.Replace(...可能会生成一个无效的字符串,因为它可能会损坏某些需要反斜杠正确表示的特殊字符。

这种类型的转义字符串通常是在已经是JSON字符串的字符串再次序列化时生成的(甚至更多次)。这会导致类似“各种级别的序列化”的情况。(它实际上是一个带有保留字符的字符串的序列化),结果是反哈希字符(或一组,两个或多个反斜杠:\,\,\)分散在字符串中。因此,正确地删除它们并不足以将它们替换为空。

正确的方法:获得未转义字符串的更好方法是首先将其转换为字符串类型(如果需要,请重复多次),然后将其转换为目标字符串类型:

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

wtlkbnrh

wtlkbnrh2#

在重新配置过程之前尝试string contentCorrected = contentCorrected.Replace(@"\", "");

w6mmgewl

w6mmgewl3#

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

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

字符串

noj0wjuj

noj0wjuj4#

1.删除所有\字符,然后再重新格式化。使用替换函数。

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

字符串
2.您的JSON字符串不完整或似乎不是List<Dictionary<string, string>>"类型。请更正您希望转换的JSON类型。我对您的JSON进行了如下修改,并成功运行。

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

u1ehiz5o

u1ehiz5o5#

对我来说,下面的代码工作

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

字符串

相关问题