examples/reflection/reflection_query_to_custom_json.rs
1//! Same example as `query_to_json`, but with customized serializer parameters
2
3use crate::z_ignore_test_common::*;
4
5use flecs_ecs::prelude::*;
6use flecs_ecs::sys;
7use json::IterToJsonDesc;
8
9#[derive(Component)]
10#[flecs(meta)]
11pub struct Position {
12 pub x: f32,
13 pub y: f32,
14}
15
16#[derive(Component)]
17#[flecs(meta)]
18pub struct Velocity {
19 pub x: f32,
20 pub y: f32,
21}
22
23#[derive(Component)]
24#[flecs(meta)]
25pub struct Mass {
26 pub value: f32,
27}
28
29fn main() {
30 let world = World::new();
31
32 world
33 .entity_named("a")
34 .set(Position { x: 10.0, y: 20.0 })
35 .set(Velocity { x: 1.0, y: 2.0 });
36
37 world
38 .entity_named("b")
39 .set(Position { x: 20.0, y: 30.0 })
40 .set(Velocity { x: 2.0, y: 3.0 });
41
42 world
43 .entity_named("c")
44 .set(Position { x: 30.0, y: 40.0 })
45 .set(Velocity { x: 3.0, y: 4.0 })
46 .set(Mass { value: 10.0 });
47
48 world
49 .entity_named("d")
50 .set(Position { x: 30.0, y: 40.0 })
51 .set(Velocity { x: 4.0, y: 5.0 })
52 .set(Mass { value: 20.0 });
53
54 // Query for components
55 let q = world.new_query::<(&mut Position, &Velocity)>();
56
57 // Serialize query to JSON. Customize serializer to only serialize entity names and component values.
58 let desc = IterToJsonDesc {
59 serialize_values: true,
60 serialize_fields: true,
61 ..Default::default()
62 };
63
64 println!("{}", q.iterable().to_json(Some(&desc)).unwrap());
65
66 // Output:
67 // {
68 // "results": [
69 // {
70 // "name": "a",
71 // "fields": {
72 // "values": [
73 // {
74 // "x": 10,
75 // "y": 20
76 // },
77 // {
78 // "x": 1,
79 // "y": 2
80 // }
81 // ]
82 // }
83 // },
84 // {
85 // "name": "b",
86 // "fields": {
87 // "values": [
88 // {
89 // "x": 20,
90 // "y": 30
91 // },
92 // {
93 // "x": 2,
94 // "y": 3
95 // }
96 // ]
97 // }
98 // },
99 // {
100 // "name": "c",
101 // "fields": {
102 // "values": [
103 // {
104 // "x": 30,
105 // "y": 40
106 // },
107 // {
108 // "x": 3,
109 // "y": 4
110 // }
111 // ]
112 // }
113 // },
114 // {
115 // "name": "d",
116 // "fields": {
117 // "values": [
118 // {
119 // "x": 30,
120 // "y": 40
121 // },
122 // {
123 // "x": 4,
124 // "y": 5
125 // }
126 // ]
127 // }
128 // }
129 // ]
130 // }
131}
132
133#[cfg(feature = "flecs_nightly_tests")]
134#[test]
135fn test() {
136 let output_capture = OutputCapture::capture().unwrap();
137 main();
138 output_capture.test("reflection_query_to_custom_json".to_string());
139}