以与JSON键不同的方式格式化struct字段

时间:2015-05-01 03:19:41

标签: rust

Rust的rustc-serialize包允许在某些情况下通过分别从 ImageIcon BPawn; ImageIcon WPawn; JLabel Label = new JLabel[8][8] //2D array of labels that gives each spot a position. public void setPieces(){ //set up pawns in their respective positions. BPawn = new ImageIcon("Images/BPawn.png", "BPawn"); WPawn = new ImageIcon("Images/WPawn.png", "WPawn"); for(int i=0;i<Label[0].length;i++){ Label[1][i].setIcon(BPawn); Label[6][i].setIcon(WPawn); }//end for }//end setPieces. RustcEncodable派生自动将结构序列化或反序列化为JSON。例如,以下结构:

RustcDecodable

将表示为此JSON:

#[derive(RustcEncodable, RustcDecodable)]
struct Person {
    first_name: String,
    last_name: String,
    age: u8,
}

我需要反序列化一些使用camel-cased键的JSON。这似乎要求struct字段的命名方式相似,它会发出编译器警告,结构字段应该是蛇形的。我可以用{ "first_name": "Joe", "last_name": "Shmoe", "age": 30 } 来警告这个警告,但我更喜欢用蛇形结构字段。有没有办法在不使用#[allow(non_snake_case)] / ToJson / Encodable特征手动实现JSON序列化/反序列化的情况下执行此操作?

1 个答案:

答案 0 :(得分:4)

不,#[derive]基础架构根本没有提供自定义的机会。

但是,您可以通过#[derive]了解rustc -Z unstable-options --pretty expanded内容扩展到的内容:

#![feature(no_std)]
#![no_std]
#[prelude_import]
use std::prelude::v1::*;
#[macro_use]
extern crate std as std;
struct Person {
    first_name: String,
    last_name: String,
    age: u8,
}
#[automatically_derived]
impl ::rustc_serialize::Decodable for Person {
    fn decode<__D: ::rustc_serialize::Decoder>(__arg_0: &mut __D)
     -> ::std::result::Result<Person, __D::Error> {
        __arg_0.read_struct("Person", 3usize, |_d| -> _ {
                            ::std::result::Result::Ok(Person{first_name:
                                                                 match _d.read_struct_field("first_name",
                                                                                            0usize,
                                                                                            ::rustc_serialize::Decodable::decode)
                                                                     {
                                                                     ::std::result::Result::Ok(__try_var)
                                                                     =>
                                                                     __try_var,
                                                                     ::std::result::Result::Err(__try_var)
                                                                     =>
                                                                     return ::std::result::Result::Err(__try_var),
                                                                 },
                                                             last_name:
                                                                 match _d.read_struct_field("last_name",
                                                                                            1usize,
                                                                                            ::rustc_serialize::Decodable::decode)
                                                                     {
                                                                     ::std::result::Result::Ok(__try_var)
                                                                     =>
                                                                     __try_var,
                                                                     ::std::result::Result::Err(__try_var)
                                                                     =>
                                                                     return ::std::result::Result::Err(__try_var),
                                                                 },
                                                             age:
                                                                 match _d.read_struct_field("age",
                                                                                            2usize,
                                                                                            ::rustc_serialize::Decodable::decode)
                                                                     {
                                                                     ::std::result::Result::Ok(__try_var)
                                                                     =>
                                                                     __try_var,
                                                                     ::std::result::Result::Err(__try_var)
                                                                     =>
                                                                     return ::std::result::Result::Err(__try_var),
                                                                 },}) })
    }
}
#[automatically_derived]
impl ::rustc_serialize::Encodable for Person {
    fn encode<__S: ::rustc_serialize::Encoder>(&self, __arg_0: &mut __S)
     -> ::std::result::Result<(), __S::Error> {
        match *self {
            Person {
            first_name: ref __self_0_0,
            last_name: ref __self_0_1,
            age: ref __self_0_2 } =>
            __arg_0.emit_struct("Person", 3usize, |_e| -> _ {
                                match _e.emit_struct_field("first_name",
                                                           0usize, |_e| -> _ {
                                                           (*__self_0_0).encode(_e)
                                                       }) {
                                    ::std::result::Result::Ok(__try_var) =>
                                    __try_var,
                                    ::std::result::Result::Err(__try_var) =>
                                    return ::std::result::Result::Err(__try_var),
                                };
                                match _e.emit_struct_field("last_name",
                                                           1usize, |_e| -> _ {
                                                           (*__self_0_1).encode(_e)
                                                       }) {
                                    ::std::result::Result::Ok(__try_var) =>
                                    __try_var,
                                    ::std::result::Result::Err(__try_var) =>
                                    return ::std::result::Result::Err(__try_var),
                                };
                                return _e.emit_struct_field("age", 2usize,
                                                            |_e| -> _ {
                                                            (*__self_0_2).encode(_e)
                                                        }); }),
        }
    }
}

是的,它非常笨拙,都像那样扩展,但它可以很容易地折叠并改变以适应:

impl Decodable for Person {
    fn decode<D: Decoder>(decoder: &mut D) -> Result<Person, D::Error> {
        decoder.read_struct("Person", 3, |d| Ok(Person {
            first_name: try!(d.read_struct_field("firstName", 0, Decodable::decode)),
            last_name: try!(d.read_struct_field("lastName", 1, Decodable::decode)),
            age: try!(d.read_struct_field("age", 2, Decodable::decode)),
        }))
    }
}

impl Encodable for Person {
    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
        s.emit_struct("Person", 3, |e| {
            try!(e.emit_struct_field("firstName", 0, |e| self.first_name.encode(e)));
            try!(e.emit_struct_field("lastName", 1, |e| self.last_name.encode(e)));
            e.emit_struct_field("age", 2, |e| self.age.encode(e))
        })
    }
}