How to deserialize multiline string?

I want to deserialize the following string

let source = r#"{
    "id": "0",
    "title": { "type": "text", "content": "What is MonQ?" },
    "question": [
        { "type": "text", "content": "What is MonQ?" }
    ],
    "answer": [
        { "type": "text", "content": "MonQ is ..." },
        { "type": "math", "content": "$$ \frac{a}{b} $$" },
        { "type": "rust", "content": "pub enum State {
            Start,
            Transient,
            Closed
        }" }
    ]
}"#;

into

use serde::{Deserialize, Serialize};

pub type QuizID = String;

#[derive(Deserialize, Serialize, Clone)]
pub struct Quiz {
    pub id: QuizID,
    pub title: Cell,
    pub question: Vec<Cell>,
    pub answer: Vec<Cell>,
}

#[derive(Deserialize, Serialize, Clone)]
pub struct Cell {
    pub r#type: String,
    pub content: String,
}

The error is raised at the third items in the answer list.

"control character (\u0000-\u001F) found while parsing a string"

This doesn't happen with json macro in serde_json. I want to share the same data type between backend(actix-web) and frontend(seed), so it not enough.

Is there any way to deserialize multiline string?

AFAIK JSON doesn't allow control characters like newlines. You'll need to format source so that it doesn't contain any strings with newlines, replacing them with "\n" instead. I expect the json! macro probably does this escaping automatically.

1 Like

Small fix: doesn't allow newlines in string literals, as it is in the content field with rust type.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.