[英]How to deserialize JSON object of multiple key value entries to custom struct in Rust
[英]How to deserialize &str struct field from JSON in Rust
我正在从JSON反序列化结构:
fn main() {
let raw_json = r#"{"error": {"msg": "I am an error message"}}"#;
let error: Error = json::decode(raw_json).unwrap();
}
struct Error {
message: &'static str
}
impl<D: Decoder<E>, E> Decodable<D, E> for Error {
fn decode(d: &mut D) -> Result<Error, E> {
d.read_struct("error", 1, |d| {
Ok(Error{
message: try!(d.read_struct_field("msg", 0u, |d| Decodable::decode(d)))
})
})
}
}
但是得到这个错误:
failed to find an implementation of trait serialize::serialize::Decodable<D,E> for &'static str
向message
添加生存期无济于事。 原来&str
没有可Decodable
特征的实现,而只有String可以实现
如何将JSON反序列化为&str
struct字段?
引用不能序列化或反序列化。 需要一种不同的方法。
您的Error结构体包含一个&'static str
。 这意味着您还可以以枚举的形式表示错误,可以将其序列化。 然后,您可以实现Show for Error。
extern crate serialize;
use serialize::{Decodable, Encodable};
use std::fmt;
#[deriving(Encodable, Decodable)]
enum Error {
Foo,
Bar
}
impl fmt::Show for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Foo => write!(f, "Foo happened"),
Bar => write!(f, "Bar happened"),
}
}
}
问题是这是否真的是您想要的。 如果您希望能够表示任意错误消息(而不是特定的错误类型),则必须使用String。
extern crate serialize;
use serialize::{Decodable, Encodable};
#[deriving(Encodable, Decodable)]
struct Error {
msg: String
}
对于&'static str
,您必须具有字符串文字,该字符串在整个过程的整个生命周期内持续存在(永远存在)。 这显然是无法实现的。
一般而言,对于&'a str
,字节必须拥有其他内容-它通常是对String
某些内容的引用(它也可能是Vec<Ascii>
或外面的另一个类似UTF-8字符串类型标准库)。 这不是序列化工作的方式-不一定将值永久存储在任何地方,因此它不能产生引用。 这就是为什么只为String
实现的原因:您根本无法为&str
拥有它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.