简体   繁体   English

如何在Rust中从JSON反序列化&str结构字段

[英]How to deserialize &str struct field from JSON in Rust

I'm deserializing a struct from JSON: 我正在从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)))
      })
    })
  }
}

But getting this error: 但是得到这个错误:

failed to find an implementation of trait serialize::serialize::Decodable<D,E> for &'static str

Adding lifetime to message does not help. message添加生存期无济于事。 Turns out there is no implementation of Decodable trait for &str , but only for String 原来&str没有可Decodable特征的实现,而只有String可以实现

How do I deserialize my JSON into &str struct field? 如何将JSON反序列化为&str struct字段?

References can't be serialized or deserialized. 引用不能序列化或反序列化。 A different approach is needed. 需要一种不同的方法。

Your Error struct contains a &'static str . 您的Error结构体包含一个&'static str This means you could also represent errors in the form of an enum, which can be serialized. 这意味着您还可以以枚举的形式表示错误,可以将其序列化。 Then you could implement Show for Error. 然后,您可以实现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"),
        }
    }
}

The question is whether this is actually what you wanted. 问题是这是否真的是您想要的。 If you want the ability to represent an arbitrary error message (rather than a specific error type) then you'll have to use String. 如果您希望能够表示任意错误消息(而不是特定的错误类型),则必须使用String。

extern crate serialize;
use serialize::{Decodable, Encodable};

#[deriving(Encodable, Decodable)]
struct Error {
    msg: String
}

For &'static str , you must have a string literal, a string that lasts for lifetime of the entire process (aka forever). 对于&'static str ,您必须具有字符串文字,该字符串在整个过程的整个生命周期内持续存在(永远存在)。 This evidently can't be achieved. 这显然是无法实现的。

For &'a str in general, something else must be owning the bytes—it is a reference to some of the contents of a String , in general (it might also be Vec<Ascii> or possibly another similar UTF-8 string type outside the standard library). 一般而言,对于&'a str ,字节必须拥有其他内容-它通常是对String某些内容的引用(它也可能是Vec<Ascii>或外面的另一个类似UTF-8字符串类型标准库)。 This is not the way in which the serialization works—there is not necessarily a value stored anywhere permanent, so it can't produce references. 这不是序列化工作的方式-不一定将值永久存储在任何地方,因此它不能产生引用。 This is why it's only implemented for String : you simply cannot have it for &str . 这就是为什么只为String实现的原因:您根本无法为&str拥有它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM