我一直在尝试反序列化包含一个对象的 JSON,该对象的值只能是字符串、布尔值或数字。
这是我使用的代码:
use serde::{Deserialize, Serialize};
use serde_json::Number;
use std::collections::HashMap;
#[derive(Deserialize, Debug, Serialize, Clone)]
pub enum OtherValue {
Bool(bool),
Number(Number),
Text(String),
}
#[derive(Deserialize, Debug, Serialize)]
pub struct Item {
numbers: HashMap<String, Number>,
others: HashMap<String, OtherValue>,
}
如果您想尝试,这是我进行的测试
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_deserialize_with_numbers() {
let input_str = r#"
{
"numbers": {
"key": 12.34
},
"others": {}
}
"#;
let output = serde_json::from_str::<Item>(input_str).unwrap();
assert_eq!(output.numbers.keys().len(), 1);
assert_eq!(output.others.keys().len(), 0);
}
#[test]
fn test_deserialize_with_strings() {
let input_str = r#"
{
"numbers": {
"key": "trololo"
},
"others": {}
}
"#;
let output = serde_json::from_str::<Item>(input_str);
assert_eq!(output.is_err(), true);
}
#[test]
fn test_deserialize_with_boolean_field() {
let input_str = r#"
{
"numbers": {
"key": true
},
"others": {}
}
"#;
let output = serde_json::from_str::<Item>(input_str);
assert_eq!(output.is_err(), true);
}
#[test]
fn test_deserialize_with_array_field() {
let input_str = r#"
{
"numbers": {
"key": ["trollo", true, 42]
},
"others": {}
}
"#;
let output = serde_json::from_str::<Item>(input_str);
assert_eq!(output.is_err(), true);
}
#[test]
fn test_deserialize_with_number_tag() {
let input_str = r#"
{
"others": {
"key": 42
},
"numbers": {}
}
"#;
let output = serde_json::from_str::<Item>(input_str).unwrap();
assert_eq!(output.others.contains_key("key"), true);
}
#[test]
fn test_deserialize_with_string_tag() {
let input_str = r#"
{
"others": {
"key": "trololo"
},
"numbers": {}
}
"#;
let output = serde_json::from_str::<Item>(input_str).unwrap();
assert_eq!(output.others.contains_key("key"), true);
}
#[test]
fn test_deserialize_with_boolean_tag() {
let input_str = r#"
{
"others": {
"key": true
},
"numbers": {}
}
"#;
let output = serde_json::from_str::<Item>(input_str).unwrap();
assert_eq!(output.others.contains_key("key"), true);
}
}
但显然这不能正常工作,我无法反序列化OtherValue
.
你知道我该怎么做吗?
如果您想尝试这里是一个游乐场https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=67b43cfd4d12efc6641f5b7fba02889a