json - Rust 和 JSON 序列化

标签 json serialization rust

如果 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/

相关文章:

javascript - 是否有任何原因导致 json 在 eval 时返回字符串中的最后一个对象

c# - 无法将 JSON 数组反序列化为类型

rust - 预生成大量数据的 “queue”以便立即在actix-web端点中获取它

rust - 如何在过程宏中处理枚举/结构/字段属性?

php - PDO SQL 单查询、多行和值

arrays - 无法使用 Swift 4.0 将检索到的 JSON 复制到简单的整数数组中

javascript - 搜索对象的更好方法

java - 根据 GSON 中的值从序列化中排除某些字段

c# - 如果可为 null 的属性为 null 或为空,如何从序列化中忽略它?

rust - 如何将源文件捆绑为一个文件?