序列化到 json yaml

  1. // Serde crate 是 Serde 生态的核心。
  2. // serde_derive crate 提供的必要工具,
  3. // 使用过程宏来派生 Serialize 和 Deserialize
  4. // 使用 serde 只提供序列化和反序列化的框架,具体的操作还需要依赖具体的包。
  5. // 如 serde_json、serde_toml 等
  6. // serde = { version = "1.0.125", features = ["derive"] } 该方式可以不使用 serde_derive
  7. use serde::{Deserialize, Serialize};
  8. #[derive(Serialize, Deserialize, Debug)]
  9. struct ServerConfig {
  10. workers: u64,
  11. ignore: bool,
  12. auth_server: Option<String>,
  13. }
  14. fn main() {
  15. let config = ServerConfig {
  16. workers: 8,
  17. ignore: true,
  18. auth_server: Some("auth.server.io".to_string()),
  19. };
  20. {
  21. println!("json");
  22. let serialized = serde_json::to_string(&config).unwrap();
  23. println!("json: {}", serialized);
  24. let deserialzied: ServerConfig = serde_json::from_str(&serialized).unwrap();
  25. println!("config: {:#?}", deserialzied);
  26. }
  27. {
  28. println!("yaml");
  29. let serialized = serde_yaml::to_string(&config).unwrap();
  30. println!("yaml: {}", serialized);
  31. let deserialzied: ServerConfig = serde_yaml::from_str(&serialized).unwrap();
  32. println!("config: {:#?}", deserialzied);
  33. }
  34. }
  35. // 可以实现自定义 serialize deserialize trait

一个 demo

客户端将一个结构体序列化后发送到服务端
server.rs

  1. use serde::{Deserialize, Serialize};
  2. use serde_json;
  3. use std::io::{self, prelude::*, BufReader, Write};
  4. use std::net::{TcpListener, TcpStream};
  5. use std::{str, thread};
  6. #[derive(Debug, Deserialize, Serialize)]
  7. struct Point3D {
  8. x: i32,
  9. y: i32,
  10. z: i32,
  11. }
  12. fn handle_client(stream: TcpStream) -> io::Result<()> {
  13. println!("incomming connenction from : {}", stream.peer_addr()?);
  14. let mut buffer = Vec::new();
  15. let mut stream = BufReader::new(stream);
  16. loop {
  17. buffer.clear();
  18. let bytes_read = stream.read_until(b'\n', &mut buffer)?;
  19. if bytes_read == 0 {
  20. return Ok(());
  21. }
  22. let input: Point3D = serde_json::from_slice(&buffer)?;
  23. let value = input.x.pow(2) + input.y.pow(2) + input.z.pow(2);
  24. let value = serde_json::to_vec(&f64::from(value).sqrt())?;
  25. stream.get_mut().write(&value)?;
  26. stream.get_mut().write("\n".as_bytes())?;
  27. stream.get_mut().flush()?;
  28. }
  29. }
  30. fn main() -> io::Result<()> {
  31. let listener = TcpListener::bind("127.0.0.1:8080")?;
  32. for stream in listener.incoming() {
  33. match stream {
  34. Err(e) => println!("error: {}", e),
  35. Ok(stream) => {
  36. thread::spawn(move || {
  37. handle_client(stream).unwrap_or_else(|error| eprint!("error:{:?}", error));
  38. });
  39. }
  40. }
  41. }
  42. Ok(())
  43. }

client.rs

  1. use serde::{Deserialize, Serialize};
  2. use serde_json;
  3. use std::io::{self, prelude::*, BufReader, Write};
  4. use std::net::{TcpListener, TcpStream};
  5. use std::{str, thread};
  6. #[derive(Debug, Deserialize, Serialize)]
  7. struct Point3D {
  8. x: i32,
  9. y: i32,
  10. z: i32,
  11. }
  12. fn main() -> anyhow::Result<()> {
  13. let mut stream = TcpStream::connect("127.0.0.1:8080")?;
  14. loop {
  15. let mut input = String::new();
  16. let mut buffer = Vec::new();
  17. io::stdin()
  18. .read_line(&mut input)
  19. .expect("Failed to read from stdin");
  20. let parts: Vec<&str> = input.trim_matches('\n').split(',').collect();
  21. let point = Point3D {
  22. x: parts[0].parse().unwrap(),
  23. y: parts[1].parse().unwrap(),
  24. z: parts[2].parse().unwrap(),
  25. };
  26. stream
  27. .write_all(serde_json::to_string(&point).unwrap().as_bytes())
  28. .expect("failed to write");
  29. stream.write_all(b"\n")?;
  30. let mut reader = BufReader::new(&stream);
  31. reader.read_until(b'\n', &mut buffer)?;
  32. let input = str::from_utf8(&buffer)?;
  33. if input == "" {
  34. eprintln!("Empty response");
  35. }
  36. println!("response ::{}", input);
  37. }
  38. }