0

I'm doing what I assume to be a very common thing and have value-type structs that will be serialized to JSON and deserialized from JSON. Is there a way to do that with #[derive()]?

For a struct Foo:

#[derive(Serialize, Deserialize/*, JsonSerialize??, JsonDeserialize??*/)
struct Foo {
  a: String,
  b: i64,
  c: Vec<u8>,
  d: HashMap<String, String>
  e: MyEnum
}

It should generate something like:

impl TryFrom<Value> for Foo {
  fn try_from(v: Value) -> Result<Foo, Error> {
    serde_json::from_value(v)
  }
}

impl Into<Value> for Foo {
  fn into(self) -> Value {
    serde_json::to_value(self)
  }
}

impl TryFrom<String> for Foo {
  fn try_from(v: String) -> Result<Foo, Error> {
    Foo::try_from(serde_json::to_value(v))
  }
}

impl Into<String> for Foo {
  fn into(self) -> String {
    serde_json::to_string(self)
  }
}

Is there any need for try_from::<String>() and into::<String>()?

Jacob Phillips
  • 8,841
  • 3
  • 51
  • 66
  • 4
    I don't understand what you're trying to achieve. `Serialize` and `Deserialize` give you JSON ser/de for free, not need for additional traits. – Chayim Friedman Jul 10 '23 at 16:51
  • 3
    Aside: you should never implement `Into` just implement `From for String` (or preferably `Display` in this specific case) and `From for Value`. – cafce25 Jul 10 '23 at 17:10
  • @ChayimFriedman Using what methods? Do I always need to use serde_json:: methods or can I use try_from() and into()? – Jacob Phillips Jul 10 '23 at 17:35
  • Using no methods at all. Normally you're just going to use `serde_json::{from_str, to_string}` and not implement any `From` or `Into`. Reason being that `serde_json::Value` isn't very fast or memory-efficient. – Caesar Jul 10 '23 at 22:48
  • Maybe an [example](https://docs.rs/serde_json/latest/serde_json/#parsing-json-as-strongly-typed-data-structures) can clear things up? – Caesar Jul 11 '23 at 01:08

0 Answers0