Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(de)serialization from struct #1913

Open
MartinVerges opened this issue Apr 14, 2023 · 0 comments
Open

(de)serialization from struct #1913

MartinVerges opened this issue Apr 14, 2023 · 0 comments

Comments

@MartinVerges
Copy link

I just learned from https://github.com/nlohmann/json that they have an excellent macro for struct serialization. If possible, I would love to see something like that in ArduinoJson to ease working with structs. Here is how they do it:

Define a struct following macro in it:

NLOHMANN_DEFINE_TYPE_INTRUSIVE(Struct-name, member1, member2,...)

This will add everything needed for nlohmann::json to (de)serialize this struct.

struct Tower{
    std::string name;
    int type_id;
    float range;

    NLOHMANN_DEFINE_TYPE_INTRUSIVE(Tower, name, type_id, range)
};

// Create an instance
Tower tower{"Tower",1895,18.95f};

// convert to JSON, just by assigning:
nlohmann::json json = tower;

// convert to string
std::string json_as_string = json.dump()

// convert to bson (a more compact format)
std::vector<std::uint8_t> as_bson = nlohmann::json::to_bson(json);

To create a json or instance from this data:

// string to json
nlohmann::json back_json = nlohmann::json::parse(json_as_string);

// bson to json (from std::vector<std::uint8_t>)
auto from_bson_json1 = nlohmann::json::from_bson(bson_data);
// bson to json (having void* and size)
auto from_bson_json2 = nlohmann::json::from_bson(bson_data,bson_data+size);

// json -> instance
auto tower = back_json.get<Tower>();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant