diff --git a/src/value/mod.rs b/src/value/mod.rs index b3f51ea0d..ad8c7f252 100644 --- a/src/value/mod.rs +++ b/src/value/mod.rs @@ -256,6 +256,12 @@ impl Display for Value { } } +impl AsRef for Value { + fn as_ref(&self) -> &Value { + self + } +} + fn parse_index(s: &str) -> Option { if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) { return None; @@ -987,8 +993,13 @@ where /// "location": "Menlo Park, CA" /// }); /// -/// let u: User = serde_json::from_value(j).unwrap(); +/// // from_value accepts both reference ... +/// let u: User = serde_json::from_value(&j).unwrap(); /// println!("{:#?}", u); +/// +/// // ... and moved value +/// let u2: User = serde_json::from_value(j).unwrap(); +/// println!("{:#?}", u2); /// } /// ``` /// @@ -1001,9 +1012,9 @@ where /// is wrong with the data, for example required struct fields are missing from /// the JSON map or some number is too big to fit in the expected primitive /// type. -pub fn from_value(value: Value) -> Result +pub fn from_value>(value: V) -> Result where T: DeserializeOwned, { - T::deserialize(value) + T::deserialize(value.as_ref()) } diff --git a/tests/regression/issue520.rs b/tests/regression/issue520.rs index 730ecc60a..dcbbad62c 100644 --- a/tests/regression/issue520.rs +++ b/tests/regression/issue520.rs @@ -12,7 +12,7 @@ enum E { fn test() { let e = E::Float(159.1); let v = serde_json::to_value(e).unwrap(); - let e = serde_json::from_value::(v).unwrap(); + let e = serde_json::from_value::(v).unwrap(); match e { E::Float(f) => assert_eq!(f, 159.1), diff --git a/tests/regression/issue795.rs b/tests/regression/issue795.rs index 411e8af5d..a0ef5e710 100644 --- a/tests/regression/issue795.rs +++ b/tests/regression/issue795.rs @@ -58,5 +58,5 @@ fn test() { assert!(serde_json::from_str::(s).is_err()); let j = json!({"Variant":{"x":0,"y":0}}); - assert!(serde_json::from_value::(j).is_err()); + assert!(serde_json::from_value::(j).is_err()); } diff --git a/tests/test.rs b/tests/test.rs index c18254a85..580ff299f 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -1899,13 +1899,13 @@ fn test_integer_key() { (r#"{"123 ":null}"#, "expected `\"` at line 1 column 6"), ]); - let err = from_value::>(json!({" 123":null})).unwrap_err(); + let err = from_value::, Value>(json!({" 123":null})).unwrap_err(); assert_eq!( err.to_string(), "invalid value: expected key to be a number in quotes", ); - let err = from_value::>(json!({"123 ":null})).unwrap_err(); + let err = from_value::, Value>(json!({"123 ":null})).unwrap_err(); assert_eq!( err.to_string(), "invalid value: expected key to be a number in quotes",