在 C# 中从 JSON 字符串(包含特殊字符)反序列化时出现问题

问题描述 投票:0回答:1

我在 C# 中有以下 JSON :

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

如您所见,我正在尝试反序列化。我已经经历了 thisthis 但在我的情况下它不起作用,因为正如您所看到的

example
属性中有很多特殊字符导致反序列化给我带来了很多麻烦。我尝试用
\"
和“”替换反引号(就在示例属性开始之后以及末尾),但似乎没有任何效果。我不断收到错误。

我还应该做什么来反序列化上述字符串? 非常感谢。

c# json .net serialization deserialization
1个回答
0
投票

使用字符串文字直接在代码中定义包含许多特殊字符的字符串。您可以通过将字符串括在三重引号(或更多,如果需要)中来完成此操作。

示例:

string someText = """This is a text
with line breaks and some special characters
\ / @ ' "
"""
© www.soinside.com 2019 - 2024. All rights reserved.