Skip to content

C++ 11: Unable to use try / catch optional field with in JSON arrays #859

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

Open
Daveyjonez opened this issue Apr 7, 2025 · 1 comment
Open

Comments

@Daveyjonez
Copy link

In C++ 11, it seems that a try / catch is the only way of achieving optional values. This works with singular JSON objects, but as soon as they are included in a JSON array, the optional-ness fails and is the NVP becomes required for all objects in the array. Is there any workaround for this use case?

Code to reproduce:

#include "cereal/archives/json.hpp"
#include "cereal/cereal.hpp"
#include "cereal/types/vector.hpp"
#include "gtest/gtest.h"

class foo
{
public:
    size_t number {0};
    bool optional {true};

    template<class Archive>
    void serialize(Archive &ar)
    {
        ar(CEREAL_NVP(number));

        // Optional Overrides
        try {
            ar(CEREAL_NVP(optional));
        }
        catch (...){
            std::cout << "Skipping optional" << std::endl;
        }
    }
};


class bar{

public:
    std::vector<foo> foos;

    template<class Archive>
    void serialize(Archive &ar)
    {
        ar(CEREAL_NVP(foos));
    }
};

TEST(ARR_TEST, test) {
    // passes
    const std::string foo_str = R"({
        "test": {"number":1}
    })";
    foo f;
    {
        std::istringstream is(foo_str);
        cereal::JSONInputArchive archive(is);
        archive(f);
    }
    EXPECT_EQ(f.number, 1);
    EXPECT_TRUE(f.optional);

    // fails
    const std::string bar_str = R"({
        "test": {
            "foos": [{"number":1}, {"number": 2}]
        }
    })";
    bar b;
    {
        std::istringstream is(bar_str);
        cereal::JSONInputArchive archive(is);
        archive(b);
    }
    EXPECT_EQ(b.foos.size(), 2);
}
@redchairman
Copy link

redchairman commented Apr 7, 2025 via email

@Daveyjonez Daveyjonez changed the title Unable to use try / catch optional field with in JSON arrays C++ 11: Unable to use try / catch optional field with in JSON arrays Apr 7, 2025
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