How Rust saves json data to a file

use serde::{Deserialize, Serialize};

use serde_json;

use std::{fs,io::Write};

#[derive(Debug, Serialize, Deserialize)]

struct CityWeather {

    name: String,

    temp: [i32; 2],

    temps: Vec<i32>,

}

fn  get_json() {

    let beijing = CityWeather {

        name: "Beijing".to_string(),

        temp: [23, 31],

        temps: vec![31, 30, 32, 30, 30],

    };

    let sdata = serde_json::to_string(&beijing);

    if sdata.is_err() {

        println!("Error, filed to Serialize structure {}", sdata.unwrap_err());

        std::process::exit(1);

    }

    let sdata = sdata.unwrap();

    println!("Serialized data: {}", sdata);

}

fn main()  {

    get_json();

    let mut f = fs::File::create("test.json").expect("Failed to create");

    f.write_all(b"hello workes sdsdsd1r").expect("Failed to write");

    // f.sync_all();

    // Ok(())

}

What is the question?

2 Likes

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.