Skip to main content

examples/reflection/
reflection_basics_json.rs

1use crate::z_ignore_test_common::*;
2
3use flecs_ecs::prelude::*;
4
5#[derive(Debug, Component)]
6#[flecs(meta)]
7pub struct Position {
8    pub x: f32,
9    pub y: f32,
10}
11
12fn main() {
13    let mut world = World::new();
14
15    /* Alternatively without the meta attribute,
16    you can do it manually like so (without the derive macro)
17    .member(f32::id(),"x", 1 /* count */, core::mem::offset_of!(Position, x))
18    .member(f32::id(),"y", 1, core::mem::offset_of!(Position, y));
19    */
20
21    // Create a new entity with the Position component
22    let e = world.entity().set(Position { x: 2.0, y: 4.0 });
23
24    // Convert position component to JSON string
25    e.get::<&Position>(|p| {
26        let expr: String = world.to_json::<Position>(p);
27        println!("Position: {expr}");
28    });
29
30    // Output:
31    //  Position: {x: 2, y: 4}
32
33    // Convert entity to JSON string
34    println!("Entity: {}", e.to_json(None));
35
36    // Output:
37    // Entity: {"name":"#547", "components":{"Position":{"x":2, "y":4}}}
38}
39
40#[cfg(feature = "flecs_nightly_tests")]
41#[test]
42fn test() {
43    let output_capture = OutputCapture::capture().unwrap();
44    main();
45    output_capture.test("reflection_basics_json".to_string());
46}