序列化/反序列化

142 篇文章 0 订阅
118 篇文章 1 订阅

Golang在标准库内置了 包用来实现JSON编码/解码功能。我们可以定义可以轻松读取和写入JSON的类型。下面一个例子:

{
"id": 3137,
"author": {
"id": 420,
"name": "Chongchong"
},
"body": "Hello,This is Chongchong web!",
"in_reply_to": 3135
}

在Golang中,可以生成如下的结构体:

type Author struct {
ID int `json:"id"`
Name string `json:"name"`
}

 

type Comment struct {
ID int `json:"id"`
Author Author `json:"author"`
Body string `json:"body"`
InReplyTo int `json:"in_reply_to"`
}

Rust没有开箱即用的功能,需要使用第三方板条箱,最常用的一个库是serde,可以跨JSON和能想到的所有其他序列化方法使用。

[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"

注意,上面serde的依赖配置,和其他包有差异。

Golang的JSON包通过使用struct标签作为元数据来工作,但是Rust没有,需要改用Rust的衍生功能。

因此,要将serde用于的注释类型:

use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Author {
pub id: i32,
pub name: String,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Comment {
pub id: i32,
pub author: Author,
pub body: String,
pub in_reply_to: i32,
}

然后,使用以下代码解析Json:

fn main() {
let data = r#"
{
"id": 3137,
"author": {
"id": 420,
"name": "Chongchong"
},
"body": "Hello,This is Chongchong web!",
"in_reply_to": 3135
}
"#;
let c: Comment = serde_json::from_str(data).expect("json to parse");
println!("comment: {:#?}", c);
}

cargo run

...
Finished dev [unoptimized + debuginfo] target(s) in 0.04s
     Running `target/debug/serdeex`
comment: Comment {
    id: 3137,
    author: Author {
        id: 420,
        name: "Chongchong",
    },
    body: "Hello,This is Chongchong web!",
    in_reply_to: 3135,
}

 

Golang和Rust语言常见功能/库

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值