You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中反序列化含特殊字符的JSON字符串遇阻

问题:C#中JSON反序列化含特殊字符的example字段失败

问题场景

现有一段包含C代码的JSON字符串,其中example字段包含大量特殊字符(换行、双引号、符号等),尝试反序列化时持续报错,替换反引号等操作无效。

原始JSON字符串(C#硬编码写法)

string extractedText = "   [
      {
        \"mainQuestion\": \"Question 5: Attempt Any 2 [5 x 2 = 10]\",
        \"question\": \"Write a C program to define a structure called student that contains the following members: name, age, and marks. Then, create an array of students and print the details of all students.\",
        \"marks\": \"5\",
        \"correctAnswer\": \"To solve this problem, we can define a structure called `student` that contains three members: `name`, `age`, and `marks`. Then, we can create an array of students and use a loop to print the details of each student. Here is an example program that demonstrates how this can be done:\",
        \"example\": `
    #include <stdio.h>
    
    // Define the student structure
    struct student {
        char name[50];
        int age;
        float marks;
    };
    
    // Create an array of students
    struct student students[3];
    
    // Get the details of each student from the user
    for (int i = 0; i < 3; i++) {
        printf(\"Enter the name of student %d: \", i + 1);
        scanf(\"%s\", students[i].name);
    
        printf(\"Enter the age of student %d: \", i + 1);
        scanf(\"%d\", &students[i].age);
    
        printf(\"Enter the marks of student %d: \", i + 1);
        scanf(\"%f\", &students[i].marks);
    }
    
    // Print the details of all students
    printf(\"\nDetails of all students:\\n\");
    for (int i = 0; i < 3; i++) {
        printf(\"\nStudent %d:\\n\", i + 1);
        printf(\"Name: %s\\n\", students[i].name);
        printf(\"Age: %d\\n\", students[i].age);
        printf(\"Marks: %.2f\\n\", students[i].marks);
    }
    `
      }
    ]\"

现有类及反序列化代码

public class QuestionAnswer
{
    public string mainQuestion { get; set; }
    public string question { get; set; }
    public string marks { get; set; }
    public string correctAnswer { get; set; }
    public string example { get; set; }
}
var questionsandAnswers = JsonConvert.DeserializeObject<QuestionAnswer>(extractedText);

问题分析

  1. JSON格式不合法:标准JSON要求字符串必须用双引号"包裹,而example字段使用了反引号`,不符合JSON规范。
  2. 反序列化类型不匹配:JSON外层是数组[],但代码中尝试反序列化为单个QuestionAnswer对象,类型不匹配。
  3. 特殊字符未正确转义:C#字符串中的双引号、换行等字符未正确转义,导致JSON本身语法错误。

解决方法

步骤1:修正JSON格式

将example字段的反引号替换为双引号,并正确转义内部的所有双引号(改为\"),同时处理换行和特殊字符。如果是C#硬编码字符串,建议使用逐字字符串(@"")简化转义。

步骤2:修正反序列化目标类型

将目标类型改为List<QuestionAnswer>或QuestionAnswer[],匹配JSON的数组结构。

修正后的代码示例

修正后的JSON字符串(C#逐字字符串写法)

string extractedText = @"[
    {
        ""mainQuestion"": ""Question 5: Attempt Any 2 [5 x 2 = 10]"",
        ""question"": ""Write a C program to define a structure called student that contains the following members: name, age, and marks. Then, create an array of students and print the details of all students."",
        ""marks"": ""5"",
        ""correctAnswer"": ""To solve this problem, we can define a structure called `student` that contains three members: `name`, `age`, and `marks`. Then, we can create an array of students and use a loop to print the details of each student. Here is an example program that demonstrates how this can be done:"",
        ""example"": ""#include <stdio.h>\n\n// Define the student structure\nstruct student {\n    char name[50];\n    int age;\n    float marks;\n};\n\n// Create an array of students\nstruct student students[3];\n\n// Get the details of each student from the user\nfor (int i = 0; i < 3; i++) {\n    printf(\"\"Enter the name of student %d: \"\", i + 1);\n    scanf(\"\"%s\"\", students[i].name);\n\n    printf(\"\"Enter the age of student %d: \"\", i + 1);\n    scanf(\"\"%d\"\", &students[i].age);\n\n    printf(\"\"Enter the marks of student %d: \"\", i + 1);\n    scanf(\"\"%f\"\", &students[i].marks);\n}\n\n// Print the details of all students\nprintf(\"\"\nDetails of all students:\n\"\");\nfor (int i = 0; i < 3; i++) {\n    printf(\"\"\nStudent %d:\n\"\", i + 1);\n    printf(\"\"Name: %s\n\"\", students[i].name);\n    printf(\"\"Age: %d\n\"\", students[i].age);\n    printf(\"\"Marks: %.2f\n\"\", students[i].marks);\n}\n""
    }
]";

修正后的反序列化代码

public class QuestionAnswer
{
    public string mainQuestion { get; set; }
    public string question { get; set; }
    public string marks { get; set; }
    public string correctAnswer { get; set; }
    public string example { get; set; }
}

// 反序列化为列表,匹配JSON数组结构
var questionsandAnswers = JsonConvert.DeserializeObject<List<QuestionAnswer>>(extractedText);

额外说明

如果JSON是从外部来源(文件、API接口)获取,无需手动转义,只需确保源JSON符合标准规范:

  • 所有字符串用双引号包裹
  • 字符串内部的双引号必须转义为\"
  • 换行和特殊字符可由JSON解析器自动处理

内容的提问来源于stack exchange,提问作者S M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 11:54:53