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

How do I remove excess layers #820

Open
zgmslm opened this issue Mar 23, 2024 · 1 comment
Open

How do I remove excess layers #820

zgmslm opened this issue Mar 23, 2024 · 1 comment

Comments

@zgmslm
Copy link

zgmslm commented Mar 23, 2024

When I use cereal:

#include <iostream>  
#include <sstream>  
#include <cereal/types/string.hpp>  
#include <cereal/archives/json.hpp>  

struct person
{
    std::string name;
    int age;

    template <class Archive>
    void serialize(Archive & archive)
    {
        archive(CEREAL_NVP(name), CEREAL_NVP(age));
    }
};

int main()
{
    person p = { "Alice", 30 };

    std::stringstream ss;
    {
        cereal::JSONOutputArchive archive(ss);
        archive(p);
    }
 
    std::string json_string = ss.str();
    std::cout << "Serialized JSON: \n" << json_string << std::endl;

    return 0;
}

I expect to serialize to the string:
{ "name": "Alice", "age": 30 }

But the serialized string is:

{
    "value0": {
        "name": "Alice",
        "age": 30
    }
}

cereal adds an additional layer to the top object, How do I use cereal to generate json with no additional layers?

@dimateos
Copy link

In general, I think you cant.

Cereal is expecting more than a single "Person" to be serialized, so it writes an outer json where it puts each of the serialized objects.

You can name each object using CEREAL_NVP direclty at archive(p); to overwrite the default keyname "value0".
Or for this toy example you could get no additional layers by manually serializing each field from outside:
archive(cereal::make_nvp("name", p.name), cereal::make_nvp("age", p.age));... but not very escalable.

I believe Cereal is more for serializing the state of your app, preferably in binary archives but you have human readable for simple cases / debugging purposes. Is not really suited for loading/writing config files.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants