USCiLab / cereal

A C++11 library for serialization
BSD 3-Clause "New" or "Revised" License
4.18k stars 751 forks source link

The closing parenthesis is missing after serializing to JSON to write to the file #797

Closed blueoblue closed 1 year ago

blueoblue commented 1 year ago
#include<fstream>
#include <cereal/types/map.hpp>
#include <cereal/types/vector.hpp>
#include <cereal/types/string.hpp>

#include <cereal/archives/json.hpp>
#include <iostream>

class Model {
    private:
        using tp=std::map<std::string, std::vector<float>>;
        tp data;
    public:
        Model()=default;
        Model(tp &&dt): data(dt) {}
        tp &get() {
            return data;
        }
        template<class Archive>
        void save(Archive & archive) const
        {
            archive(data); 
        }

        template<class Archive>
        void load(Archive & archive)
        {
            archive(data); 
        }
};

int main() {
    std::ofstream ofile("a.json");
    Model m;
    Model md({{"a", {1.0, 2.0, 3.0}}, {"b", {1.5, 2.5}}});
    cereal::JSONOutputArchive ar(ofile);
    cereal::JSONOutputArchive aro(std::cout);
    auto ser=CEREAL_NVP(md);

    ar( ser);
    aro(ser);
//    ofile.close();
}

aro will write to standrand output, arwrite to a.json file.as follows: > std out and a.json:

{
    "md": {
        "value0": [
            {
                "key": "a",
                "value": [
                    1.0,
                    2.0,
                    3.0
                ]
            },
         ...
        ]
    }
}

But when I uncommented(it's ofile.close()), the closing brackets at the end of the file were missing: > a.json:

{
    "md": {
        "value0": [
            {
                "key": "a",
                "value": [
                    1.0,
                    2.0,
                    3.0
                ]
            },
         ...
        ]
    }

environment: gcc (Ubuntu 11.3.0-1ubuntu1~22.04.1) 11.3.0 cereal 1.3.2

blueoblue commented 1 year ago

I found that this topic already has an answer(https://github.com/USCiLab/cereal/issues/101), But I don't have permission to delete this issue,i'm sorry.