serde

How to build json arrays or objects dynamically with serde_json?

我的梦境 提交于 2021-01-29 12:30:51
问题 I need to build a json object at runtime. For now, just a simple {"key": "stringvalue"} object. But each key/val pair must be added in a loop. This seems really simple/basic, but I didn't find any good examples or docs on it. I did finally manage to make something work, but it seems too convoluted to be the right way. Can anyone post a working example? 回答1: You can do this with serde_json::Value : use serde_json::{Map, Value}; let mut map = Map::new(); // assuming keys_vals is a Vec<(String,

How to flatten a `Vec` field when serializing a struct with serde?

谁都会走 提交于 2021-01-29 04:45:22
问题 I've got some XML that has a tag containing multiple sibling tags with the same name, like so: <foo> <bar/> <bar/> </foo> (There may also be multiple top level <foo> s as well, though I've not gotten around to trying to (de)serialize that yet.) Using this code: use serde::{Deserialize, Serialize}; use quick_xml::de::from_str; use quick_xml::se::to_string; #[derive(Debug, Deserialize, PartialEq, Serialize)] pub struct Foo { #[serde(rename = "bar", default)] bars: Vec<Bar>, } #[derive(Debug,

Deserialize variable meta object with serde

十年热恋 提交于 2021-01-28 12:21:44
问题 I am looking an elegant way to deserialize the following input: { "products": [ { "id": 1, "ptype": "Clothes", "description": "some data about clothes", "metadata": { "colors" : ["blue", "green"], "web": false, "size": 2 } }, { "id": 4, "ptype": "Food", "description": "text for foods", "metadata": { "country": "France", "wine": true } }, { "id": 12, "ptype": "EmptyPlaceholder", "description": "nothing at all", "metadata": { } } ] } The json contains an array of products. A product can be

What is the fastest correct way to detect that there are no duplicates in a JSON array?

 ̄綄美尐妖づ 提交于 2021-01-27 22:19:21
问题 I need to check if all items are unique in an array of serde_json::Value . Since this type does not implement Hash I came up with the following solution: use serde_json::{json, Value}; use std::collections::HashSet; fn is_unique(items: &[Value]) -> bool { let mut seen = HashSet::with_capacity(items.len()); for item in items.iter() { if !seen.insert(item.to_string()) { return false; } } true } fn main() { let value1 = json!([1, 2]); assert!(is_unique(&value1.as_array().unwrap())); let value2 =

How to borrow a field for serialization but create it during deserialization?

自闭症网瘾萝莉.ら 提交于 2021-01-27 19:27:02
问题 I have a struct like this: #[derive(Serialize, Deserialize)] struct Thing { pub small_header: Header, pub big_body: Body, } I want to serialize this Thing to send over the network. I already have a Body available but I can't move it (imagine I am doing something with it, and every now and then I receive a command to temporarily stop what I'm doing and send over whatever data I have now) and I can't copy it (it's too big, possibly hundreds of megabytes). So I'd like Serde to just borrow the

Why do I get an UnsupportedType error when serializing to TOML with a manually implemented Serialize for an enum with struct variants?

纵饮孤独 提交于 2021-01-27 07:00:11
问题 I'm trying to implement Serialize for an enum that includes struct variants. The serde.rs documentation indicates the following: enum E { // Use three-step process: // 1. serialize_struct_variant // 2. serialize_field // 3. end Color { r: u8, g: u8, b: u8 }, // Use three-step process: // 1. serialize_tuple_variant // 2. serialize_field // 3. end Point2D(f64, f64), // Use serialize_newtype_variant. Inches(u64), // Use serialize_unit_variant. Instance, } With that in mind, I proceeded to

Why do I get an UnsupportedType error when serializing to TOML with a manually implemented Serialize for an enum with struct variants?

只谈情不闲聊 提交于 2021-01-27 06:55:35
问题 I'm trying to implement Serialize for an enum that includes struct variants. The serde.rs documentation indicates the following: enum E { // Use three-step process: // 1. serialize_struct_variant // 2. serialize_field // 3. end Color { r: u8, g: u8, b: u8 }, // Use three-step process: // 1. serialize_tuple_variant // 2. serialize_field // 3. end Point2D(f64, f64), // Use serialize_newtype_variant. Inches(u64), // Use serialize_unit_variant. Instance, } With that in mind, I proceeded to

How can we write a generic function for checking Serde serialization and deserialization?

我与影子孤独终老i 提交于 2021-01-26 03:23:43
问题 In a project where custom Serde (1.0) serialization and deserialization methods are involved, I have relied on this test routine to check whether serializing an object and back would yield an equivalent object. // let o: T = ...; let buf: Vec<u8> = to_vec(&o).unwrap(); let o2: T = from_slice(&buf).unwrap(); assert_eq!(o, o2); Doing this inline works pretty well. My next step towards reusability was to make a function check_serde for this purpose. pub fn check_serde<T>(o: T) where T: Debug +

How can we write a generic function for checking Serde serialization and deserialization?

谁说胖子不能爱 提交于 2021-01-26 03:22:57
问题 In a project where custom Serde (1.0) serialization and deserialization methods are involved, I have relied on this test routine to check whether serializing an object and back would yield an equivalent object. // let o: T = ...; let buf: Vec<u8> = to_vec(&o).unwrap(); let o2: T = from_slice(&buf).unwrap(); assert_eq!(o, o2); Doing this inline works pretty well. My next step towards reusability was to make a function check_serde for this purpose. pub fn check_serde<T>(o: T) where T: Debug +

How can I support an unknown or other value for a Serde enum?

六眼飞鱼酱① 提交于 2021-01-19 04:04:42
问题 I have a JSON API that returns an object that looks like this: { "PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp" } To capture this, I have an enum and a struct: #[derive(Eq, PartialEq, Deserialize, Serialize, Debug)] #[serde(rename_all = "snake_case")] pub enum PortType { Sctp, Tcp, Udp, } #[derive(Deserialize, Serialize, Debug)] #[serde(rename_all = "PascalCase")] pub struct PortMapping { pub private_port: u16, pub public_port: u16, #[serde(rename = "Type")] pub port_type: PortType, }