< 返回版块

zydxhs 发表于 2021-01-26 22:28

Tags:serde,serde_json

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

结构体,想序列化为如下的样式,serde 支持吗,应该怎么实现?

{
  "Person": {
    "name": "john",
    "age": 33
  }
}

评论区

写评论
snylonue 2021-01-30 11:59

Serialize 手动实现这个 trait?我没试过

spacemeowx2 2021-01-29 03:45

估计可以用tag

作者 zydxhs 2021-01-27 21:38

就是不想这样套一层,才在这里求助呢。不过,还是谢谢!

--
👇
c5soft:

use serde_derive::Serialize;
#[derive(Debug, Serialize)]
struct Person {
    name: String,
    age: i32,
}

#[derive(Debug, Serialize)]
struct PersonContainer {
    person: Person,
}

fn main() {
    let p = PersonContainer {
        person: Person {
            name: "john".into(),
            age: 33,
        },
    };

    // Convert the Point to a JSON string.
    let serialized = serde_json::to_string(&p).unwrap();

    println!("serialized = {:?}", serialized);
}

c5soft 2021-01-27 07:41
use serde_derive::Serialize;
#[derive(Debug, Serialize)]
struct Person {
    name: String,
    age: i32,
}

#[derive(Debug, Serialize)]
struct PersonContainer {
    person: Person,
}

fn main() {
    let p = PersonContainer {
        person: Person {
            name: "john".into(),
            age: 33,
        },
    };

    // Convert the Point to a JSON string.
    let serialized = serde_json::to_string(&p).unwrap();

    println!("serialized = {:?}", serialized);
}

1 共 4 条评论, 1 页