[英]Why Error(“trailing characters”) when trying to deserialize a JSON file to a hashmap?
So basically, I'm trying to deserialize a JSON file into a hashmap<String,String> using the serde crate, but.所以基本上,我正在尝试使用 serde crate 将 JSON 文件反序列化为 hashmap<String,String> ,但是。 The JSON file:
JSON 文件:
"
[
{
"orchard_name": "Happy Apple",
"tons": "5"
},
{
"orchard_name": "Munch for Lunch",
"tons": "2"
}
]
"
This is my structure:这是我的结构:
#[derive(Serialize, Deserialize, Debug)]
struct OrangeFarm
{
map : HashMap<String,String>
}
and this is where I try to do the deserialization:这就是我尝试进行反序列化的地方:
let res = serde_json::from_str(_json);
if res.is_ok() {println!("Deserealization worked."); }
else { println!("it went wrong"); }
let mut deserializedFarm : OrangeFarm = res.unwrap();
For some reason, it works if I delete the second {}, but it doesn't if I let the second {} as I get this error "thread 'main' panicked at 'called Result::unwrap()
on an Err
value: Error("trailing characters". Do you have any idea why this happens? Thank you!出于某种原因,如果我删除第二个 {},它会起作用,但如果我让第二个 {} 则不起作用,因为我收到此错误“线程 'main' 在
Err
值上调用Result::unwrap()
时惊慌失措:错误(“尾随字符”。你知道为什么会发生这种情况吗?谢谢!
For some reason, it works if I delete the second {}, but it doesn't if I let the second {}
出于某种原因,如果我删除第二个 {},它会起作用,但如果我让第二个 {} 则不会
I have no idea what this means, but as far as I can see it never works: you're trying to deserialise an array of structures but you're deserialising to a structure.我不知道这意味着什么,但据我所知,它永远不会起作用:您正在尝试反序列化一组结构,但您正在反序列化为一个结构。 So the deserialisation logically fails.
所以反序列化在逻辑上失败了。 The code always panics, though in the initial case it also prints "it went wrong".
代码总是恐慌,尽管在最初的情况下它也会打印“它出错了”。
Furthermore, your structure definition doesn't match the JSON so even if you try deserializing to a Vec<OrangeFarm>
the call will fail: serde
expects to find a map
attribute, which is not present in the JSON.此外,您的结构定义与 JSON 不匹配,因此即使您尝试反序列化为
Vec<OrangeFarm>
调用也会失败: serde
期望找到map
属性,该属性不存在于 Z0ECD1FD8C1D7ABBD1874A 中。 So you need to either fix your structure, or configure the serialisation / deserialisation scheme.所以你需要修复你的结构,或者配置序列化/反序列化方案。
Deserializing to a Vec<HashMap<String, String>>
would work but I've no idea whether that is your intent.反序列
Vec<HashMap<String, String>>
会起作用,但我不知道这是否是您的意图。
That aside:除此之外:
is_ok
/ is_err
then immediately unwrap, instead you'd use match
or if let
to cleanly do both at the same time and avoid the risk of desync, misunderstanding, etc... there are situations where unwrap
.is_ok
/ is_err
然后立即展开,而是使用match
或if let
同时干净地执行这两项操作,并避免不同步、误解等的风险......有些情况下unwrap
。_json
is abnormal, the _
prefix is intended for variables you want to capture but don't want to use (it suppresses the unused_variables
lint without dropping the value immediately, which would be the effect of a lone _
)._json
是异常的, _
前缀用于您想要捕获但不想使用的变量(它会抑制未使用的unused_variables
lint 而不会立即删除该值,这将是一个单独的效果_
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.