serde

How to (de)serialize a strongly typed JSON dictionary in Serde?

北城余情 提交于 2019-12-10 18:06:14
问题 I am writing a Rust application that handles JSON messages from a TypeScript client with a public interface. I have written some code using serde_derive and it works well, but I can't figure out how to implement dictionaries; e.g.: { "foo" : { "data" : 42 }, "bar" : { "data" : 1337 } } Here the keys are the strings "foo" and "bar" and the dictionary's values follow this schema: use serde_derive; use serde_json::Number; #[derive(Serialize, Deserialize)] struct DictionaryValue { data: Number, }

How do I write a Serde Visitor to convert an array of arrays of strings to a Vec<Vec<f64>>?

好久不见. 提交于 2019-12-10 16:10:46
问题 I need to deserialize a JSON into a struct that has a Vec<Vec<f64>> field. The JSON has strings for numbers so I need a custom deserializer to convert the strings to f64 during the deserialization. A sample JSON that I'd like to deserialize: { "values": [["2", "1.4"], ["8.32", "1.5"]] } My struct is this: #[derive(Deserialize)] struct Payload { #[serde(default, deserialize_with = "from_array_of_arrays_of_strs")] values: Vec<Vec<f64>>, } I saw you could probably do this with visitors in the

How to deserialize “NaN” as `nan` with serde_json?

南笙酒味 提交于 2019-12-10 10:08:18
问题 I have datatypes which look like this: #[derive(Serialize, Deserialize, Debug)] #[serde(rename_all = "camelCase")] pub struct Matrix { #[serde(rename = "numColumns")] pub num_cols: usize, #[serde(rename = "numRows")] pub num_rows: usize, pub data: Vec<f64>, } My JSON bodies look something like this: { "numRows": 2, "numColumns": 1, "data": [1.0, "NaN"] } This is the serialization provided by Jackson (from a Java server we use), and is valid JSON. Unfortunately if we call serde_json::from_str(

Why does serde_json::from_reader take ownership of the reader?

帅比萌擦擦* 提交于 2019-12-09 03:32:29
问题 My code: fn request_add<T>(request: &mut Request, collection_name: &'static str) -> Fallible<Fallible<String>> where T: serde::Serialize + serde::de::DeserializeOwned, { let add_dao = dao::MongoDao::new(collection_name); let obj = serde_json::from_reader::<Body, T>(request.body)?; //cannot move out of borrowed content Ok(add_dao.add(&obj)) } I have a cannot move out of borrowed content error, because request is a reference, but why does serde_json::from_reader not use a mut reference? Why

How can I ignore extra tuple items when deserializing with Serde? (“trailing characters” error)

女生的网名这么多〃 提交于 2019-12-08 15:44:43
问题 Serde ignores unknown named fields when deserializing into regular structs. How can I similarly ignore extra items when deserializing into tuple structs (e.g. from a heterogeneous JSON array)? For example, this code ignores the extra "c" field just fine: #[derive(Serialize, Deserialize, Debug)] pub struct MyStruct { a: String, b: i32 } fn test_deserialize() -> MyStruct { ::serde_json::from_str::<MyStruct>(r#" { "a": "foo", "b": 123, "c": "ignore me" } "#).unwrap() } // => MyStruct { a: "foo",

Rust & Serde JSON deserialization examples?

让人想犯罪 __ 提交于 2019-12-08 14:46:00
问题 I'm trying to figure out how to deserialize JSON into a structure using Serde. For instance, the example JSON on serde_json's own documentation contains the following data: { "FirstName": "John", "LastName": "Doe", "Age": 43, "Address": { "Street": "Downing Street 10", "City": "London", "Country": "Great Britain" }, "PhoneNumbers": [ "+44 1234567", "+44 2345678" ] } Now, if we assume that the above data is in a variable "input" and the following piece of code: let deserialized_data: Data =

Is there a way to omit wrapper/root objects when deserializing objects with Serde?

孤者浪人 提交于 2019-12-08 07:29:18
问题 I have the following object: { "data": { "id": 1, "name": "South America", "countries": { "data": [ { "id": 122, "name": "Brazil", "capital": "Brasilia" } ] } } } I'd like to define two structs, Continent and Country , omitting the data wrappings which don't add value. 回答1: I would implement this using a wrapper struct that can be used directly for dropping the top level of nesting as well as through a #[serde(with = "...")] attribute for eliminating levels of nesting within the deserialized

How to deserialize into a enum variant based on a key name?

一曲冷凌霜 提交于 2019-12-07 12:01:06
问题 I have JSON which takes two forms: "Example:" { "field": 42, "A": 76 } "Example:" { "field": 42, "B": 110 } I want to deserialize it into a struct like this: struct Example { field: i32, an_enum: AnEnum, } where enum AnEnum { A(i32), B(i32), } I don't know how to do it without writing a custom deserializer for Example . This works: "Example:" { "field": 42, "an_enum": {"A": 76} } or, in YAML: Example: field: 42 an_enum: A: 76 The an_enum is superfluous and annoying to write. How can I

Is there a way to deserialize arbitrary JSON using Serde without creating fine-grained objects?

元气小坏坏 提交于 2019-12-06 17:14:26
问题 I have a JSON object that contains a few metadata keys and a large data payload. My service cares about the metadata for the purposes of logging and routing, but does not care about the payload, other than to pass the payload off to another service. I will never need to look inside the payload for any reason. Right now, the payload is represented in my struct as a serde_json::Value . Through profiling, I've seen the (de)serialization of the Value takes a non-trivial amount of time. Is there a

Is there a way to omit wrapper/root objects when deserializing objects with Serde?

自古美人都是妖i 提交于 2019-12-06 15:33:56
I have the following object: { "data": { "id": 1, "name": "South America", "countries": { "data": [ { "id": 122, "name": "Brazil", "capital": "Brasilia" } ] } } } I'd like to define two structs, Continent and Country , omitting the data wrappings which don't add value. dtolnay I would implement this using a wrapper struct that can be used directly for dropping the top level of nesting as well as through a #[serde(with = "...")] attribute for eliminating levels of nesting within the deserialized data structure. use serde::{Deserialize, Deserializer}; #[derive(Deserialize, Debug)] struct