Skip to content
Flecs v4.1
reflection/ser_std_string

  • C++

    View on GitHub

    1#include <ser_std_string.h>
    2#include <iostream>
    3#include <string>
    4
    5// This example shows how to serialize a component with an std::string
    6
    7struct StringComponent {
    8 std::string a;
    9 std::string b;
    10};
    11
    12int main(int, char *[]) {
    13 flecs::world ecs;
    14
    15 // Register reflection for std::string
    16 ecs.component<std::string>()
    17 .opaque(flecs::String) // Opaque type that maps to string
    18 .serialize([](const flecs::serializer *s, const std::string *data) {
    19 const char *str = data->c_str();
    20 return s->value(flecs::String, &str); // Forward to serializer
    21 })
    22 .assign_string([](std::string* data, const char *value) {
    23 *data = value; // Assign new value to std::string
    24 });
    25
    26 // Register component with std::string members
    27 ecs.component<StringComponent>()
    28 .member<std::string>("a")
    29 .member<std::string>("b");
    30
    31 // Create value & serialize it
    32 StringComponent v = {"foo", "bar"};
    33 std::cout << ecs.to_json(&v) << std::endl;
    34
    35 // Deserialize new strings into value
    36 ecs.from_json(&v, "{\"a\": \"hello\", \"b\": \"world\"}");
    37 std::cout << "{a: " << v.a << ", b: " << v.b << "}" << std::endl;
    38
    39 // Output:
    40 // {"a": "foo", "b": "bar"}
    41 // {a: "hello", b: "world"}
    42}
    component & opaque(const Func &type_support)
    Register an opaque type interface.
    Definition component.inl:8
    const char * from_json(flecs::entity_t tid, void *value, const char *json, flecs::from_json_desc_t *desc=nullptr)
    Deserialize a value from JSON.
    Definition world.hpp:42
    flecs::string to_json(flecs::entity_t tid, const void *value) const
    Serialize an untyped value to JSON.
    Definition world.hpp:12
    ecs_serializer_t serializer
    Serializer object, used for serializing opaque types.
    Definition opaque.hpp:19
    flecs::component< T > component(Args &&... args) const
    Find or register a component.
    Definition impl.hpp:11
    int(*) value(const struct ecs_serializer_t *ser, ecs_entity_t type, const void *value)
    Serialize value.
    Definition meta.h:350
    The world.
    Definition world.hpp:129