0

I need some extra type information on a URL, so I've created a UrlWithPhantomdata struct with a value field for the URL and a PhantomData field. How can I deserialize a string into this struct with Serde?

More specifically, given this JSON object:

{
  "url": "https://example.com"
}

How can I deserialize it into the following ApiData struct?

#[derive(Deserialize)]
pub struct ApiData {
    url: UrlWithPhantomdata<i32>
}

#[derive(Deserialize)]
pub struct UrlWithPhantomdata<T> {
    #[serde(with = "url_serde")]
    url_value: Url,
    #[serde(skip)]
    url_type: PhantomData<T>
}

The more general problem is addressed in serde-rs/serde#1048, but I'm looking for a solution that works until that bug is fixed.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
konstin
  • 476
  • 7
  • 16
  • 1
    You haven't described what is *wrong* with the code you have. It would also be polite to [edit] your question to provide a [MCVE] so that every possible answerer didn't have to divine what `url_serde` does (or decide if it's even needed to solve the core problem). – Shepmaster Feb 15 '18 at 22:27
  • The [duplicates applied to your example](https://play.rust-lang.org/?gist=cbfadccf2dc1a3b4b4eb2279be2a4535&version=stable). TL;DR: implement `serde::Deserialize` for your type, deserialize a `Url` (a.k.a. `String`) inside that implementation, then construct a new value of your type with an appropriate `PhantomData`. – Shepmaster Feb 15 '18 at 22:37

0 Answers0