Why does Boost property tree write_json save everything as string? Is it possible to change that?

后端 未结 7 1196
忘掉有多难
忘掉有多难 2020-11-30 20:05

I\'m trying to serialize using boost property tree write_json, it saves everything as strings, it\'s not that data are wrong, but I need to cast them explicitly every time a

相关标签:
7条回答
  • 2020-11-30 20:36

    The simplest and cleanest solution that i could come up with was generating the JSON with placeholders and in the end string replacing with the actual value ditching the extra quotes.

    static string buildGetOrdersCommand() {
        ptree root;
        ptree element;
        element.put<string>("pendingOnly", ":pendingOnly");
        element.put<string>("someIntValue", ":someIntValue");
    
        root.put("command", "getOrders");
        root.put_child("arguments", element);
    
        std::ostringstream buf;
        write_json(buf, root, false);
        buf << std::endl;
    
        string json = buf.str();
        replace(json, ":pendingOnly", "true");
        replace(json, ":someIntValue", std::to_string(15));
    
        return json;
    }
    
    static void replace(string& json, const string& placeholder, const string& value) {
        boost::replace_all<string>(json, "\"" + placeholder + "\"", value);
    }
    

    And the result is

    {"command":"getOrders","arguments":{"pendingOnly":true,"someIntValue":15}}

    0 讨论(0)
提交回复
热议问题