Skip to content

Deserializing borrowed string when it contains \n escape #1413

@terhechte

Description

@terhechte

Hey!

I have this very simple example:

extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;

use std::fs::File;
use std::collections::HashMap;
use std::io::prelude::*;

#[derive(Deserialize)]
struct User<'a> {
    username: &'a str
}

#[derive(Deserialize)]
struct Comment<'a> {
    author: User<'a>,
    text: &'a str,
    likes: Vec<User<'a>>
}

#[derive(Deserialize)]
struct Media<'a> {
    author: User<'a>,
    likes: Vec<User<'a>>,
    comments: Vec<Comment<'a>>,
    images: HashMap<String, String>,
    description: &'a str
}

fn conv<'a>(string: &'a str) -> Vec<&'a str> {
    let media: Vec<Media> = serde_json::from_str(&string).unwrap();
    media.into_iter().map(|x|x.author.username).collect::<Vec<&str>>()
}

fn main() {
    let mut f = File::open("./test.json").expect("file not found");
    let mut contents = String::new();
    f.read_to_string(&mut contents).expect("something went wrong reading the file");
    println!("{:?}", &conv(&contents));
}

This is the input json:

[{"images": {"small": "http://appventure.me/small.png", "medium": "http://appventure.me/medium.png"}, "description": {"text": "Duis quam lorem, lacinia nec tempus non, Sondra Swigart tristique", "likes": [{"username": "Loan"}, {"username": "Shaneka"}], "author": {"username": "Hattie"}}, "likes": [{"username": "Les"}, {"username": "Vance"}, {"username": "Marilee"}], "comments": [{"text": "dictum feugiat. Ut blandit volutpat Kandis Ammerman ante in commodo.", "likes": [{"username": "Les"}], "author": {"username": "Les"}}, {"text": "luctus, enim lacus sagittis arcu, Clement Cassity at mollis tellus", "likes": [{"username": "Marisha"}], "author": {"username": "Liliana"}}], "author": {"username": "Debbie"}}]

I'm getting the error:

invalid type: string [...] expected a borrowed string

What did I do wrong? I did read the docs but couldn't figure it out.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions