简体   繁体   English

使用 Newtonsoft 在值中使用引号反序列化 JSON

[英]Deserializing JSON with Newtonsoft with quotes in a value

I am retrieving JSON from an API and have the following problem: Some Json-values look like this and cannot be serialized the standard way我正在从 API 检索 JSON 并遇到以下问题:一些 Json 值看起来像这样并且不能以标准方式序列化

"key": "This is just a "dummy" value to show the problem",

The problem are the quotes around dummy.问题是围绕 dummy 的引号。 Newtonsoft obviously thinks the value ends with the quote before dummy, but it actually ends after problem. Newtonsoft 显然认为该值以哑元之前的引号结尾,但实际上它是在问题之后结束的。 Is there a way to ignore those quotes or somehow remove them automatically?有没有办法忽略这些引号或以某种方式自动删除它们?

I've tried to remove them with a StringBuilder and String-Replace, but that didn't work because such a pattern occures mutliple times in the JSON-File and sometimes the nested quotes quote a single word, sometimes a whole sentence.我曾尝试使用 StringBuilder 和 String-Replace 删除它们,但这不起作用,因为这种模式在 JSON 文件中多次出现,有时嵌套引号引用单个单词,有时引用整个句子。

The whole JSON from the API has around 50.000 lines, so it's impossible to correct the error by hand. API 中的整个 JSON 大约有 50.000 行,因此无法手动更正错误。

Can this be solved somehow in C#?这可以在 C# 中以某种方式解决吗?

Update: You have to write a custom parser to parse since its clearly not JSON then.更新:您必须编写一个自定义解析器来解析,因为它显然不是 JSON。 What you have to do is fix the serialized object before you deseriliaze it.您需要做的是在反序列化之前修复序列化对象。 You have to iterate through the entire string and remove the unrequired quotes.您必须遍历整个字符串并删除不需要的引号。

An example would be when the value property of a JSON ends and next one begins there is a comma character in the middle.一个例子是当 JSON 的 value 属性结束而下一个开始时,中间有一个逗号字符。

Its basically a huge nested if condition, to fix this.它基本上是一个巨大的嵌套 if 条件,以解决此问题。

Original Answer原答案

你的榜样

As you can see, it does not parse as an valid JSON.如您所见,它不会解析为有效的 JSON。 You have to represent quotes as below.您必须按如下方式表示引号。 If its not someting in your control, you have to come up with a custom parser.如果它不在您的控制范围内,您必须想出一个自定义解析器。

带引号的有效 JSON

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

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