【问题标题】:Json array creation using boost c++使用boost c ++创建Json数组
【发布时间】:2017-09-08 18:02:28
【问题描述】:

我想使用下面的代码 sn-p 打印 json 数组,但它没有给出想要的结果。这是输出

{
    "prefix": "standard",
    "faceID": "42"
}

{
    "prefix1": "standard2",
    "faceID2": "44"
}

这是由以下代码 sn-p 产生的:

#include <boost/serialization/string.hpp>
#include <string>
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
using boost::property_tree::ptree; 
using boost::property_tree::write_json;

void create_array(ptree parent)
{
    std::stringstream oss;

    write_json(oss,parent);

    std::string serialized_strings(oss.str());

    std::cout << oss.str() << std::endl;
}

int main()                                                                                                                                                                                                 
{   

    ptree pt,pt1;

    pt.put("prefix","standard");
    pt.put("faceID",42);
    create_array(pt);
    pt1.put("prefix1","standard2");
    pt1.put("faceID2",44);
    create_array(pt1); 

}

预期输出

[
{
    "prefix": "standard",
    "faceID": "42"
},

{
    "prefix1": "standard2",
    "faceID2": "44"
}
]

【问题讨论】:

  • 拜托,即使阅读大约 20 行的文档太多了,搜索也不会那么难。
  • 亲爱的@sehe:我已经浏览了那个链接,看起来在 boost 中没有解决这个问题的方法,我不想创建数组的名称来绑定元素所以寻找替代解决方案。
  • 你现在不“想要”什么? “创建名称”?你读过the limitations in those lines of documentation吗? (链接固定)
  • 以下链接中给出的解决方案不符合我的要求。stackoverflow.com/questions/2114466/…

标签: c++ json boost


【解决方案1】:

只是说清楚:

documentation 声明

属性树数据集没有类型,不支持数组。因此,使用以下 JSON / 属性树映射 [...]

它继续描述每个ptree总是代表一个JSON对象。

您需要记住,Boost Property Tree 不是 JSON 库。它是一个属性树库,可以选择使用 JSON 的子集来实现互操作性。因此,您不能拥有任意 JSON 内容:不能拥有顶级数组、不能拥有单独的值、不能拥有实际的数字类型、null、布尔值等。

您只能序列化属性树using the described mappings

【讨论】:

  • 我完全同意你的看法。我可以理解,我们不能通过 boost 获得任意 json 的东西,这就是为什么我在我的问题中指出如何解决这个问题的原因。我们应该去其他图书馆来实现这一目标吗?
  • 是的。 (顺便说一下,我不清楚您是否想要顶级数组,也不清楚您是否正在征求替代工具的建议。顺便说一下,这个问题将是Stack Overflow 的题外话。我个人推荐rapidjson.org/md_doc_tutorial.htmlgithub.com/nlohmann/json)
  • 通过 +1 接受了这一点,但不确定为什么我的问题被标记为否决。如果其他库中提供除了 boost 仍然解决方案之外的解决方案,那么应该提出建议。
猜你喜欢
  • 1970-01-01
  • 2011-01-08
  • 2011-04-14
  • 2013-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-20
相关资源
最近更新 更多