如何使用boost库制作这种类型的json字符串

时间:2015-06-09 03:59:19

标签: json boost

    {

       "TokenNo":"Deb123456",  

        "CPUID":"Deb123456",

        "CommandID":"05",

        "CommandStatus":"null",  

        "IsEncrypted":0,  

       "CommandString":"[{\"Add\":\"97\",\"EstbCD\":\"99999999\", \"EID\": 
\"XY\", \"CID\":\"0154400000\",\"DATE\":\"14042015\", \"TIME\":\"1835
\",\"IOMODE\":\"I\",\"REASONCODE\":\"55\",\"LAT\":\"87\",\"LONG\":\"90\"}]"

    }

1 个答案:

答案 0 :(得分:4)

我现在非常喜欢这个。 1.你发一个非问题2.我发一个答案来匹配。

  

如果你想在下次自己做这个技巧,请看一下:http://paste.ubuntu.com/11665634/(基于How return leaf nodes of a boost::property_tree)。

现在为派对伎俩:

<强> Live On Coliru

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

using boost::property_tree::ptree;

int main()
{
    ptree pt;
    pt.add("TokenNo",       "Deb123456");
    pt.add("CPUID",         "Deb123456");
    pt.add("CommandID",     "05");
    pt.add("CommandStatus", "null");
    pt.add("IsEncrypted",   "0");

    ptree cs;
    cs.add("Add",           "97");
    cs.add("EstbCD",        "99999999");
    cs.add("EID",           "XY");
    cs.add("CID",           "0154400000");
    cs.add("DATE",          "14042015");
    cs.add("TIME",          "1835");
    cs.add("IOMODE",        "I");
    cs.add("REASONCODE",    "55");
    cs.add("LAT",           "87");

#if 1 // if you are a sane person
    pt.put_child("CommandString", cs);
#else
    // or, if you really wanted braindead non-JSON:
    std::ostringstream oss;
    write_json(oss, cs);

    pt.put("CommandString", oss.str());
#endif
    write_json(std::cout, pt);
}

sane people的输出:

{
    "TokenNo": "Deb123456",
    "CPUID": "Deb123456",
    "CommandID": "05",
    "CommandStatus": "null",
    "IsEncrypted": "0",
    "CommandString": {
        "Add": "97",
        "EstbCD": "99999999",
        "EID": "XY",
        "CID": "0154400000",
        "DATE": "14042015",
        "TIME": "1835",
        "IOMODE": "I",
        "REASONCODE": "55",
        "LAT": "87"
    }
}

braindead people requirements的输出:

{
    "TokenNo": "Deb123456",
    "CPUID": "Deb123456",
    "CommandID": "05",
    "CommandStatus": "null",
    "IsEncrypted": "0",
    "CommandString": "{\n    \"Add\": \"97\",\n    \"EstbCD\": \"99999999\",\n    \"EID\": \"XY\",\n    \"CID\": \"0154400000\",\n    \"DATE\": \"14042015\",\n    \"TIME\": \"1835\",\n    \"IOMODE\": \"I\",\n    \"REASONCODE\": \"55\",\n    \"LAT\": \"87\"\n}\n"
}
相关问题