Skip to content

(de)serialization from struct #1913

Open
@MartinVerges

Description

@MartinVerges

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>();

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions