@@ -3,7 +3,6 @@ use serde::{
33 de:: { self , DeserializeOwned , Unexpected } ,
44 ser,
55} ;
6- use serde_json:: Value ;
76use std:: { fmt, marker:: PhantomData } ;
87
98pub use wp_serde_date:: wp_utc_date_format;
@@ -361,15 +360,6 @@ impl<'de> de::Visitor<'de> for DeserializeStringVecOrStringAsOptionVisitor {
361360 }
362361}
363362
364- pub fn ok_or_default < ' a , T , D > ( deserializer : D ) -> Result < T , D :: Error >
365- where
366- T : Deserialize < ' a > + Default ,
367- D : Deserializer < ' a > ,
368- {
369- let v: Value = Deserialize :: deserialize ( deserializer) ?;
370- Ok ( T :: deserialize ( v) . unwrap_or_default ( ) )
371- }
372-
373363struct DeserializeEmptyVecOrNone < T > ( PhantomData < T > ) ;
374364
375365impl < ' de , T > de:: Visitor < ' de > for DeserializeEmptyVecOrNone < T >
@@ -543,20 +533,26 @@ mod tests {
543533 assert_eq ! ( expected_result, option_string_vec_or_string. string) ;
544534 }
545535
546- #[ derive( Debug , Deserialize ) ]
547- pub struct OptionStringOrBool {
548- #[ serde( deserialize_with = "ok_or_default" ) ]
549- pub value : Option < String > ,
536+ #[ derive( Debug , Deserialize , PartialEq , Eq ) ]
537+ pub struct OptionStructOrEmptyArray {
538+ #[ serde( deserialize_with = "deserialize_empty_vec_or_none" ) ]
539+ pub value : Option < OptionStructOrEmptyArrayInner > ,
540+ }
541+
542+ #[ derive( Debug , Deserialize , PartialEq , Eq ) ]
543+ pub struct OptionStructOrEmptyArrayInner {
544+ foo : String ,
550545 }
551546
552547 #[ rstest]
553- #[ case( r#"{"value": "foo"}"# , Some ( "foo" . to_string( ) ) ) ]
554- #[ case( r#"{"value": "false"}"# , Some ( "false" . to_string( ) ) ) ]
555- #[ case( r#"{"value": false}"# , None ) ]
548+ #[ case( r#"{"value": {"foo": "bar"}}"# , Some ( OptionStructOrEmptyArrayInner { foo: "bar" . to_string( ) } ) ) ]
556549 #[ case( r#"{"value": []}"# , None ) ]
557- fn test_ok_or_default ( #[ case] test_case : & str , #[ case] expected_result : Option < String > ) {
558- let option_string_or_bool: OptionStringOrBool =
550+ fn test_deserialize_empty_vec_or_none (
551+ #[ case] test_case : & str ,
552+ #[ case] expected_result : Option < OptionStructOrEmptyArrayInner > ,
553+ ) {
554+ let option_struct: OptionStructOrEmptyArray =
559555 serde_json:: from_str ( test_case) . expect ( "Test case should be a valid JSON" ) ;
560- assert_eq ! ( expected_result, option_string_or_bool . value) ;
556+ assert_eq ! ( expected_result, option_struct . value) ;
561557 }
562558}
0 commit comments