[英]How do I serialize and deserialize a tuple in Rust using Serde?
I have a tuple consisting of an String and a Uuid that I serialize using serde_json:我有一个由字符串和 Uuid 组成的元组,我使用 serde_json 对其进行序列化:
let log_and_id = (String::from("Test string"), test_id);
let log_and_id_serialized = serde_json::to_string(&log_and_id)
.expect("Serialization failed");
//After serialization (debug print): "[\"Test string\",\"32a8e12d-69d2-421d-a52e-1ee76cc03ed5\"]"
Then I transfer this serialized value over the network and receive a BytesMut (serialized_tuple) on the other end, which I try to deserialize:然后我通过网络传输这个序列化值并在另一端接收一个 BytesMut (serialized_tuple),我尝试对其进行反序列化:
//Bytesmut value (debug print): b"\"[\\\"Test string\\\",\\\"32a8e12d-69d2-421d-a52e-1ee76cc03ed5\\\"]\""
let (log, operation_state_id) = serde_json::from_slice::<(String, Uuid)>(&serialized_tuple)?;
But I get the following error:但我收到以下错误:
ERROR actix_http::response] Internal Server Error: SerdeError(Error("invalid type: string \"[\\\"Test string\\\",\\\"32a8e12d-69d2-421d-a52e-1ee76cc03ed5\\\"]\", expected a tuple of size 2", line: 1, column: 68))
(De)serializing single objects this way used to work in other parts of this code, so what could cause it to fail when used with tuples?以这种方式(反)序列化单个对象曾经在此代码的其他部分工作,那么在与元组一起使用时会导致它失败的原因是什么?
You don't have a serialized tuple, but a serialized serialized tuple.您没有序列化的元组,而是序列化的序列化元组。
I mean the serialization of the tuple, which was a JSON string, was again serialized.我的意思是元组的序列化,它是一个 JSON 字符串,再次被序列化。
You can check this with this code ( playground ):您可以使用此代码( 操场)检查这一点:
let serialized_tuple = b"\"[\\\"Test string\\\",\\\"32a8e12d-69d2-421d-a52e-1ee76cc03ed5\\\"]\"";
let serialized_tuple: String = serde_json::from_slice(serialized_tuple).unwrap();
let (log, operation_state_id) = serde_json::from_slice::<(String, String)>(serialized_tuple.as_bytes()).unwrap();
which produces the desired tuple.这会产生所需的元组。
Of course, rather than deserializing twice, you should remove the unnecessary serialization from your application (it's not in the code you've shown).当然,您应该从应用程序中删除不必要的序列化,而不是反序列化两次(它不在您显示的代码中)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.