简体   繁体   English

将具有特殊字符的Json反序列化为字典

[英]Deserialize Json with special character into dictionary

I got some trouble with a problem when use Newtonsoft json.net to deserialize json string to dictionary. 使用Newtonsoft json.net将json字符串反序列化为字典时遇到问题。 It 'sa case of my json string have some special character. 这是我的json字符串具有某些特殊字符的情况。

string jsonString = "{\"name\":\"Jones Smith\",\"age\":\"20\",\"description\":\"The one live with \"ALIGATOR\"\"}";
Dictionary<string, object> dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);

I try to find a solution in the use of json.net but i not found. 我尝试在json.net的使用中找到解决方案,但未找到。 So the FINAL plan is remove that "characters". 因此,最终计划是删除该“字符”。 So, what is the best solution for this case? 那么,这种情况的最佳解决方案是什么?

I think you can't do very much in your situation besides changing the format at the origin. 我认为,除了更改原始格式之外,您在您的情况下不能做很多事情。 The problem with your input is that there are " characters escaped the same way once in your json directly and once in your json values. 你输入的问题是,有"字在你的JSON直接,一旦躲过一次以同样的方式在你的JSON值。

Consider the following part: "description":"The one live with "ALIGATOR"" How should a deserializer know which " should be considered part of the value or part of the json format? 考虑以下部分: "description":"The one live with "ALIGATOR""反序列化器应如何知道哪个"应该被视为值的一部分或json格式的一部分?

I got the answer, like the last comment, that 's not valid JSON, below is valid JSON 我得到了答案,就像最后的评论一样,那是无效的JSON,下面是有效的JSON

{"name":"Jones Smith","age":"20","description":"The one live with \"ALIGATOR\""}

And all i can do is add '\\' before special characters if the value of field description is "The one live with "ALIGATOR"" to make a valid JSON and convert to c# like this: 我所能做的就是,如果字段描述的值是“带有“ ALIGATOR”的代码”,则在特殊字符前添加“ \\”,以生成有效的JSON并转换为c#,如下所示:

string jsonString = {\"name\":\"Jones Smith\",\"age\":\"20\",\"description\":\"The one live with \\"ALIGATOR\\"\"}

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

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