How to convert class object to json string using boost library in C++?

筅森魡賤 提交于 2019-12-05 15:01:29
sehe

This is not "fairly easy", because C++ doesn't have JSON support.

Neither does Boost:

That said, this appears to be what you want:

So, I want to convert the class object into JSON string, How can I do that ? Do I have to first put these object into a container (like vector or list) and then write it into JSON?

Yes, you put them into a tree container, namely boost::property_tree::ptree:

Live On Coliru

#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <iostream>
#include <sstream>
using boost::property_tree::ptree;

namespace Entities {

    struct POST1 {
        std::string TokenNo;
        std::string CommandStatus;
        std::string CommandID;
        std::string CPUID;
        std::string ISEncrypted;

    };

    std::string to_json(POST1 const& o) {
        ptree out;
        out.put("POST1.TokenNo",          o.TokenNo);
        out.put("POST1.CommandStatus",    o.CommandStatus);
        out.put("POST1.CommandID",        o.CommandID);
        out.put("POST1.CPUID",            o.CPUID);
        out.put("POST1.ISEncrypted",      o.ISEncrypted);

        std::ostringstream oss;
        boost::property_tree::write_json(oss, out);
        return oss.str();
    }
}

// ADL trigger; `using Entities::to_json` would be roughly equivalent, but not
// make it clear that ADL is happening
void to_json();

int main() {
    Entities::POST1 obj { "1122", "0", "00", "A1234B1234", "0" };
    std::cout << to_json(obj);
}

Output:

{
    "POST1": {
        "TokenNo": "1122",
        "CommandStatus": "0",
        "CommandID": "00",
        "CPUID": "A1234B1234",
        "ISEncrypted": "0"
    }
}
use this simple way

pt::ptree root;


    root.put("POST1 .TokenNo", "1122");
    root.put("POST1 .CommandStatus", "0");
    root.put("POST1 .CommandID", "00");
    root.put("POST1 .CPUID", "A1234B1234");
    root.put("POST1 .ISEncrypted", "0");
    // Once our ptree was constructed, we can generate JSON on standard output

    pt::write_json(std::cout, root);

OUT PUT

{ "POST1": { "TokenNo": "1122", "CommandStatus": "0", "CommandID": "00", "CPUID": "A1234B1234", "ISEncrypted": "0" } }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!