Is it possible to deserialize a raw string directly into a specific type?

Viewed 48

I've searched a bit and can't seem to find an answer for this, so this is probably a duplicate.

I have a String like this (the actual strings are not literals):

let param_type_raw = String::from("address");

I want to deserialize it into the type ethabi::ParamType, which implements the Deserializer trait. So far, I've came up with this:

let param_type: ParamType = serde_json::from_str(format!("\"{}\"", param_type_raw).as_str())?;

However, it seems extremely redundant to convert the string into a JSON string just to deserialize it into ParamType. I'm certain there must be a better way of just deserializing a String by itself.

2 Answers

There is a specific function for that:

use ethabi::{param_type::Reader, ParamType};

fn main() {
    let param_type_raw = String::from("address");

    let param_type: ParamType = Reader::read(&param_type_raw).unwrap();
    println!("{:?}", param_type);
}
Address

Answering the title more generally: There is a suite of deserializers available for each of the primitive types in the serde::de::value module that can be created with .into_deserializer() provided by the IntoDeserializer trait.

So if you have a string and you know your type can be deserialized from a string, you can do this:

use ethabi::ParamType;
use serde::de::value::Error;
use serde::de::{Deserialize, IntoDeserializer};

fn main() {
    let param_type_raw = "address";
    let param_type: Result<_, Error> = ParamType::deserialize(param_type_raw.into_deserializer());
    println!("{:?}", param_type);
}
Ok(Address)

Slightly annoying since the deserializers are generic over the error type, so you have to specify one somewhere, but that's what serde::de::value::Error is for.

Related