将JSON字符串或字符串数​​组反序列化为Vec

时间:2016-12-14 19:53:50

标签: rust serde serde-json

我正在编写一个与JSON Web API接口的包。一个端点通常会返回{ "key": ["value1", "value2"] }形式的响应,但有时键只有一个值,端点返回{ "key": "value" }而不是{ "key": ["value"] }

我想写一些通用的东西,我可以像#[serde(deserialize_with)]一样使用它:

#[derive(Deserialize)]
struct SomeStruct {
    #[serde(deserialize_with = "deserialize_string_or_seq_string")]
    field1: Vec<SomeStringNewType>,

    #[serde(deserialize_with = "deserialize_string_or_seq_string")]
    field2: Vec<SomeTypeWithCustomDeserializeFromStr>,
}

#[derive(Deserialize)]
struct SomeStringNewType(String);

struct SomeTypeWithCustomDeserializeFromStr(String);
impl ::serde::de::Deserialize for SomeTypeWithCustomDeserializeFromStr {
    // Some custom implementation here
}

如何编写deserialize_string_or_seq_string才能执行此操作?

2 个答案:

答案 0 :(得分:3)

如果您想将单个字符串或字符串列表反序列化为更通用的Vec<String>而不是自定义类型,以下是Serde 1.0的更简单的解决方案:

extern crate serde;
#[macro_use] extern crate serde_derive;
extern crate serde_json;

use std::fmt;
use std::marker::PhantomData;

use serde::de;
use serde::de::{Deserialize, Deserializer};

#[derive(Deserialize, Debug, Clone)]
pub struct Parent {
    #[serde(deserialize_with = "string_or_seq_string")]
    pub strings: Vec<String>,
}

fn main() {
    let list_of_strings: Parent = serde_json::from_str(r#"{ "strings": ["value1", "value2"] }"#).unwrap();
    println!("list of strings: {:?}", list_of_strings);
    // Prints:
    //   list of strings: Parent { strings: ["value1", "value2"] }

    let single_string: Parent = serde_json::from_str(r#"{ "strings": "value" }"#).unwrap();
    println!("single string: {:?}", single_string);
    // Prints:
    //   single string: Parent { strings: ["value"] }
}

fn string_or_seq_string<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
    where D: Deserializer<'de>
{
    struct StringOrVec(PhantomData<Vec<String>>);

    impl<'de> de::Visitor<'de> for StringOrVec {
        type Value = Vec<String>;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("string or list of strings")
        }

        fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where E: de::Error
        {
            Ok(vec![value.to_owned()])
        }

        fn visit_seq<S>(self, visitor: S) -> Result<Self::Value, S::Error>
            where S: de::SeqAccess<'de>
        {
            Deserialize::deserialize(de::value::SeqAccessDeserializer::new(visitor))
        }
    }

    deserializer.deserialize_any(StringOrVec(PhantomData))
}

此解决方案也适用于Serde的0.9版本,并进行了以下更改:

  • 删除生命期
  • SeqAccess - &gt; SeqVisitor
  • SeqAccessDeserializer - &gt; SeqVisitorDeserializer
  • MapAccess - &gt; MapVisitor
  • MapAccessDeserializer - &gt; MapVisitorDeserializer

答案 1 :(得分:0)

此解决方案适用于Serde 1.0。

我发现的方式也要求我编写一个自定义反序列化程序,因为我需要一个可以调用visitor.visit_newtype_struct来尝试反序列化新类型的程序,并且似乎没有任何内置于serde中的内容这样做。 (我期待类似ValueDeserializer系列类型的东西。)

下面是一个独立的示例。对于两个输入都正确地反序列化SomeStruct,其中一个值是字符串的JSON数组,另一个是它们只是字符串。

#[macro_use]
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;

fn main() {
    #[derive(Debug, Deserialize)]
    struct SomeStringNewType(String);

    #[derive(Debug)]
    struct SomeTypeWithCustomDeserializeFromStr(String);
    impl<'de> ::serde::Deserialize<'de> for SomeTypeWithCustomDeserializeFromStr {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: ::serde::Deserializer<'de> {
            struct Visitor;

            impl<'de> ::serde::de::Visitor<'de> for Visitor {
                type Value = SomeTypeWithCustomDeserializeFromStr;

                fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                    write!(f, "a string")
                }

                fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: ::serde::de::Error {
                    Ok(SomeTypeWithCustomDeserializeFromStr(v.to_string() + " custom"))
                }
            }

            deserializer.deserialize_any(Visitor)
        }
    }

    #[derive(Debug, Deserialize)]
    struct SomeStruct {
        #[serde(deserialize_with = "deserialize_string_or_seq_string")]
        field1: Vec<SomeStringNewType>,

        #[serde(deserialize_with = "deserialize_string_or_seq_string")]
        field2: Vec<SomeTypeWithCustomDeserializeFromStr>,
    }

    let x: SomeStruct = ::serde_json::from_str(r#"{ "field1": ["a"], "field2": ["b"] }"#).unwrap();
    println!("{:?}", x);
    assert_eq!(x.field1[0].0, "a");
    assert_eq!(x.field2[0].0, "b custom");

    let x: SomeStruct = ::serde_json::from_str(r#"{ "field1": "c", "field2": "d" }"#).unwrap();
    println!("{:?}", x);
    assert_eq!(x.field1[0].0, "c");
    assert_eq!(x.field2[0].0, "d custom");
}

/// Deserializes a string or a sequence of strings into a vector of the target type.
pub fn deserialize_string_or_seq_string<'de, T, D>(deserializer: D) -> Result<Vec<T>, D::Error>
    where T: ::serde::Deserialize<'de>, D: ::serde::Deserializer<'de> {

    struct Visitor<T>(::std::marker::PhantomData<T>);

    impl<'de, T> ::serde::de::Visitor<'de> for Visitor<T>
        where T: ::serde::Deserialize<'de> {

        type Value = Vec<T>;

        fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
            write!(f, "a string or sequence of strings")
        }

        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where E: ::serde::de::Error {

            let value = {
                // Try parsing as a newtype
                let deserializer = StringNewTypeStructDeserializer(v, ::std::marker::PhantomData);
                ::serde::Deserialize::deserialize(deserializer)
            }.or_else(|_: E| {
                // Try parsing as a str
                let deserializer = ::serde::de::IntoDeserializer::into_deserializer(v);
                ::serde::Deserialize::deserialize(deserializer)
            })?;
            Ok(vec![value])
        }

        fn visit_seq<A>(self, visitor: A) -> Result<Self::Value, A::Error>
            where A: ::serde::de::SeqAccess<'de> {

            ::serde::Deserialize::deserialize(::serde::de::value::SeqAccessDeserializer::new(visitor))
        }
    }

    deserializer.deserialize_any(Visitor(::std::marker::PhantomData))
}

// Tries to deserialize the given string as a newtype
struct StringNewTypeStructDeserializer<'a, E>(&'a str, ::std::marker::PhantomData<E>);

impl<'de, 'a, E> ::serde::Deserializer<'de> for StringNewTypeStructDeserializer<'a, E> where E: ::serde::de::Error {
    type Error = E;

    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: ::serde::de::Visitor<'de> {
        visitor.visit_newtype_struct(self)
    }

    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: ::serde::de::Visitor<'de> {
        // Called by newtype visitor
        visitor.visit_str(self.0)
    }

    forward_to_deserialize_any! {
        bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str bytes
        byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct map
        struct enum identifier ignored_any
    }
}