gpt4 book ai didi

json - Rust 和 JSON 序列化

转载 作者:行者123 更新时间:2023-11-29 08:35:51 25 4
gpt4 key购买 nike

如果 JSON 对象缺少某些字段,decode 函数会抛出异常。例如:

extern crate rustc_serialize;
use rustc_serialize::json;
use rustc_serialize::json::Json;

#[derive(RustcDecodable, RustcEncodable, Debug)]
enum MessageType {
PING,
PONG,
OPT,
}

#[derive(RustcDecodable, RustcEncodable, Debug)]
pub struct JMessage {
msg_type: String,
mtype: MessageType,
}

fn main() {
let result3 = json::decode::<JMessage>(r#"{"msg_type":"TEST"}"#);
println!("{:?}", result3);
// this will print `Err(MissingFieldError("mtype"))`

let result = json::decode::<JMessage>(r#"{"msg_type":"TEST", "mtype":"PING"}"#);
println!("{:?}", &result);
// This will print Ok(JMessage { msg_type: "TEST", mtype: PING })

let result2 = Json::from_str(r#"{"msg_type":"TEST", "mtype":"PING"}"#).unwrap();
println!("{:?}", &result2);
// this will print Object({"msg_type": String("TEST"), "mtype": String("PING")})
}
  1. 有没有办法指定结构中的某些字段是可选的?
  2. 为什么函数 from_str 不将 mtype 序列化为枚举?

最佳答案

  1. 不,没有这样的方法。为此,您需要使用 serde . Serde 还具有许多其他功能,但不幸的是,在稳定的 Rust 上它不像 rustc_serialize 那样容易使用。

  2. 那么,应该如何呢? Json::from_str 返回一个 JSON AST,它由映射、数组、字符串、数字和其他 JSON 类型组成。它根本不能包含您的枚举值。而且自然也没有办法表明您想要其他类型而不是字符串。

关于json - Rust 和 JSON 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35806069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com