简体   繁体   English

如何正确序列化/反序列化 rust?

[英]How to properly serialize/deserialize rust?

I have multiple structs that correspond to serialized/deserialized objects only known during runtime, example:我有多个结构对应于仅在运行时才知道的序列化/反序列化对象,例如:

#[derive(Serialize, Deserialize)]
struct Car{
    model: i32,
    year: i32
}

#[derive(Serialize, Deserialize)]
struct Person{
    name: String,
    age: i32
}

Then I have functions to serialize and deserialize:然后我有序列化和反序列化的功能:

fn deserialize(data: Vec<u8>){
    let msg = str::from_utf8(data);
    serde_json::from_str(msg);
}

fn serialize(&self, object: Car) -> String{
    let msg = serde_json::to_string(&object).unwrap();
    return msg;
}

How can I make the deserialize function deserialize to both Car and Person (and possibly many other different types) and return the object?如何使反序列化 function 反序列化为 Car 和 Person(可能还有许多其他不同类型)并返回 object? And how can I make the serialize function do the same thing: serialize Car, Person, and other objects (accepting these types in the attributes of the function)?我怎样才能让序列化 function 做同样的事情:序列化 Car、Person 和其他对象(在函数的属性中接受这些类型)?

You can make deserialize generic over the Deserialize trait:您可以在Deserialize特征上使deserialize化泛型:

fn deserialize<'a, T: Deserialize<'a>>(data: &'a [u8]) -> T {
    let msg = str::from_utf8(data).unwrap();
    serde_json::from_str(msg).unwrap()
}

note that you need some lifetimes, because some types needs to borrow from the deserialized string, doc .请注意,您需要一些生命周期,因为某些类型需要从反序列化字符串doc中借用。

You can make serialize generic too:您也可以使serialize通用:

fn serialize<T: Serialize>(object: &T) -> String {
    serde_json::to_string(object).unwrap()
}

playground 操场

You want to use generic functions to allow different types to be passed in, and set trait bounds to make sure the objects are able to be serialized/deserialized.您想使用泛型函数来允许传入不同的类型,并设置特征边界以确保对象能够被序列化/反序列化。 When calling serialize , the type will be inferred by the type of the parameter, but when calling deserialize , you need to use the turbofish ( ::<> ) to specify the type, if it can't be inferred.调用serialize时,会根据参数的类型推断类型,但调用deserialize时,如果无法推断,则需要使用 turbofish ( ::<> ) 指定类型。

use serde::{Serialize, Deserialize};
use std::str;

#[derive(Serialize, Deserialize)]
struct Car {
    model: i32,
    year: i32
}

#[derive(Serialize, Deserialize)]
struct Person {
    name: String,
    age: i32
}

// constrain output types to have the `Deserialize` trait
fn deserialize<'a, T>(data: &'a [u8]) -> T where T: Deserialize<'a> {
    let msg = str::from_utf8(data).unwrap();
    serde_json::from_str::<T>(msg).unwrap()
}

// shorthand for the above when `T` isn't needed in the function body
fn serialize(object: &impl Serialize) -> String {
    let msg = serde_json::to_string(object).unwrap();
    return msg;
}

fn main() {
    let car = Car { model: 7, year: 2077 };
    let person = Person { name: "Bob".to_string(), age: 42 };

    // types are infrerred from the parameters
    let car_json = serialize(&car);
    let person_json = serialize(&person);

    let _: Car = deserialize(car_json.as_bytes()); // output type can be inferred
    let _ = deserialize::<Car>(car_json.as_bytes()); // requres turbofish

    let _: Person = deserialize(person_json.as_bytes()); // works for `Person` too
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM