使用非转义双引号初始化JSON字符串

jjhzyzn0  于 2024-01-09  发布在  其他
关注(0)|答案(4)|浏览(140)

如何在C#中将JSON中的未转义双引号转换为非转义双引号?
JSON字符串示例:

  1. {
  2. "Id": "4c8e6419-f094-48a0-94f8-752ccd7f0354",
  3. "Description": "Anastasia Sfeir is a Mexican actress, singer, and model. She is best known for her roles in the telenovelas "La que no podia amar" and "Lo que la vida me robo"."
  4. }

字符串
JSON字符串看起来像这样:

  1. string json = "\n{\n \"Id\": \"78d4f53a-8614-4096-ace9-72a62dbcdbc3\",\n \"Description\": \"100 Thieves is an esports organization and lifestyle brand founded in 2016 by Matthew \"Nadeshot\" Haag.\"\n}\n";


我得到了例外,但一旦我删除了引号,它的工作。

  1. result = System.Text.Json.JsonSerializer.Deserialize<Description>(response);


我无法控制响应,所以我希望有一个简单的内置方法来处理这个问题。

3pmvbmvn

3pmvbmvn1#

您提供的示例JSON payload没有双引号。JSON字符串中的引号使用反斜杠进行转义(例如:\”)。如果您的字符串示例与网站返回的字符串完全相同,则该字符串不是有效的JSON,常规JSON解析库无法读取。
如果示例字符串有转义引号,那么它不需要任何修改就可以正常工作。问题出在你试图解析的字符串上。|
带转义引号的有效JSON示例:

  1. {
  2. "Id": "4c8e6419-f094-48a0-94f8-752ccd7f0354",
  3. "Description": "Anastasia Sfeir is a Mexican actress, singer, and model. She is best known for her roles in the telenovelas \"La que no podia amar\" and \"Lo que la vida me robo\"."
  4. }

字符串

nhhxz33t

nhhxz33t2#

如果所有JSON字符串都只有Id和Description两个属性,可以尝试使用以下代码修复JSON字符串

  1. var desc = "\"Description\":";
  2. var firstIndex = json.IndexOf(desc) + desc.Length + 1;
  3. var lastIndex=json.LastIndexOf("\"") + 1;
  4. json = json.Replace( json[firstIndex..lastIndex],JsonConvert.SerializeObject(json[(firstIndex+1)..(lastIndex-1)]));

字符串

vulvrdjw

vulvrdjw3#

使用postman先手动调用API,看看响应是否有效。
另一个问题是the JSON string exactly looks like this:。你是怎么看到json字符串的?通过调试器?
I'm getting exceptions-什么异常?提供调试细节。
你是怎么得到HttpResponse的?你是怎么把它读成一个字符串的?请提供代码,这样我们可以帮助你。

zxlwwiss

zxlwwiss4#

受@Serge answer的启发,我设计了这个方法来清理描述。由于这个JSON是来自AI聊天机器人的回复,所以有时候它并不是100%正确,这会导致所使用的代币的金钱损失。

  1. static string FixAndDeserializeJson(string json)
  2. {
  3. try
  4. {
  5. // Extract the 'Description' value using a regular expression.
  6. var descriptionPattern = @"""Description"":\s*""(.*?)""";
  7. var match = Regex.Match(json, descriptionPattern);
  8. if (match.Success)
  9. {
  10. // Get the matched group which contains the description
  11. var descriptionValue = match.Groups[1].Value;
  12. // Decode Unicode characters and remove backslashes and quotes
  13. var fixedDescription = DecodeEncodedNonAsciiCharacters(descriptionValue)
  14. .Replace("\\", "").Replace("\"", "");
  15. // Replace the old description with the fixed one in the original JSON string
  16. var fixedJson = Regex.Replace(json, descriptionPattern, $"\"Description\": \"{fixedDescription}\"");
  17. // Validate the fixed JSON by attempting to parse it.
  18. JToken.Parse(fixedJson);
  19. // If parsing is successful, return the fixed JSON
  20. return fixedJson;
  21. }
  22. else
  23. {
  24. // If the description isn't found, the JSON is likely invalid or not in the expected format
  25. return null;
  26. }
  27. }
  28. catch (Exception)
  29. {
  30. // If parsing throws an exception at any point, the JSON is invalid; return null
  31. return null;
  32. }
  33. }
  34. static string DecodeEncodedNonAsciiCharacters(string value)
  35. {
  36. return Regex.Replace(
  37. value,
  38. @"\\u(?<Value>[a-fA-F0-9]{4})",
  39. m => {
  40. return ((char)int.Parse(m.Groups["Value"].Value, System.Globalization.NumberStyles.HexNumber)).ToString();
  41. });
  42. }

字符串

展开查看全部

相关问题