Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I deserialize a comma-separated JSON string as a vector of separate strings? [duplicate]

Tags:

json

rust

serde

I would like to deserialize my incoming data from Rocket with Serde with my own deserializer for one field. The tags field is originally a string and should be deserialized into a Vec<String>. The format of the string is more-or-less comma-separated values with a special treatment of some characters.

The documentation of Serde is completely unclear for me how to treat that case. The basic structure of tags_deserialize I just copied from the documentation.

Currently my code is as follows:

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TaskDataJson {
    pub name: String,
    pub description: String,
    #[serde(deserialize_with = "tags_deserialize")]
    pub tags: Vec<String>
}

fn tags_deserialize<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
    where
        D: Deserializer<'de>,
{
    ??? - How do I access the string coming from the response and how do I set it??
}

A sample of incoming data is:

{
    "name":"name_sample",
    "description":"description_sample",
    "tags":"tag1,tag2,tag5"
}

where this should lead to:

name = "name_sample";
description = "description_sample"
tags = ["tag1", "tag2", "tag5"]
like image 801
Fabian Avatar asked Sep 05 '25 10:09

Fabian


1 Answers

A workaround is to deserialize the string sequence "tag1,tag2,tag3" as a String value and then convert it to a Vec of strings, for example:

fn tags_deserialize<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
    D: Deserializer<'de>,
{
    let str_sequence = String::deserialize(deserializer)?;
    Ok(str_sequence
        .split(',')
        .map(|item| item.to_owned())
        .collect())
}
like image 69
attdona Avatar answered Sep 08 '25 10:09

attdona