forked from toon-format/toon-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmixed_arrays.rs
More file actions
69 lines (62 loc) · 1.87 KB
/
Copy pathmixed_arrays.rs
File metadata and controls
69 lines (62 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use serde::{Deserialize, Serialize};
use serde_json::json;
use toon_format::encode_default;
#[derive(Debug, Serialize, Deserialize)]
struct MixedItems {
items: Vec<serde_json::Value>,
}
#[derive(Debug, Serialize, Deserialize)]
struct Item {
id: i32,
name: String,
#[serde(skip_serializing_if = "Option::is_none")]
extra: Option<bool>,
}
#[derive(Debug, Serialize, Deserialize)]
struct ListItems {
items: Vec<Item>,
}
pub fn mixed_arrays() {
// JSON example: Mixed / non-uniform arrays (list format)
let mixed = json!({
"items": [1, {"a": 1}, "text"]
});
println!("{}", encode_default(&mixed).unwrap());
// Struct with mixed array (using Value)
let mixed_items = MixedItems {
items: vec![
serde_json::Value::Number(1.into()),
serde_json::Value::Object({
let mut map = serde_json::Map::new();
map.insert("a".to_string(), serde_json::Value::Number(1.into()));
map
}),
serde_json::Value::String("text".to_string()),
],
};
println!("\n{}", encode_default(&mixed_items).unwrap());
// JSON example: Objects in list format: first field on hyphen line
let list_objects = json!({
"items": [
{"id": 1, "name": "First"},
{"id": 2, "name": "Second", "extra": true}
]
});
println!("\n{}", encode_default(&list_objects).unwrap());
// Struct with non-uniform objects (different fields)
let list_items = ListItems {
items: vec![
Item {
id: 1,
name: "First".to_string(),
extra: None,
},
Item {
id: 2,
name: "Second".to_string(),
extra: Some(true),
},
],
};
println!("\n{}", encode_default(&list_items).unwrap());
}