我该如何创建一个jsoncpp数组?

4

我卡在 jsoncpp 上了。我想创建这样的一个数组:

"Cords": [{"x": 10, "y": 20}, {"x": 70, "y": 40}, {"x": 15, "y": 65}]

我已经成功使用jsoncpp处理了常规的内容(见下文),但是在创建JSON数组方面卡住了。

Json::Value event;

event["name"] = "Joe";
event["Direction"]["left"]["x"] = "1338";
event["Direction"]["right"]["x"] = "1337";

编辑:
我希望在事件内打印所有内容。
我不想分别打印坐标。


你到底想实现什么?你的代码与期望的 JSON 毫不相符。 - el.pescado - нет войне
顺便提一下,这里是两个链接:http://open-source-parsers.github.io/jsoncpp-docs/doxygen/class_json_1_1_value.html#ada6ba1369448fb0240bccc36efaa46f7 和 http://open-source-parsers.github.io/jsoncpp-docs/doxygen/class_json_1_1_value.html#ac9182982c361e0ab621134d406e5f250 - el.pescado - нет войне
2个回答

5
你需要使用 operator[]int 重载来定义一个数组。
Json::Value coord(int x, int y)
{
    Json::Value result;
    result["x"] = x;
    result["y"] = y;
    return result;    
}

void make_event(Json::Value & event)
{
    Json::Value & coords = event["Cords"];
    coords[0] = coord(10, 20);
    coords[1] = coord(70, 40);
    coords[2] = coord(15, 65);
}

看起来不错,@Caleth如果我必须将其放入一个void函数中,最佳实践是什么?现在它说在“{”标记之前不允许函数定义。 - JJ Jones
coord 的定义移到使用它的函数之外。 - Caleth
正如预期的那样工作!非常感谢你的帮助! - JJ Jones

1
可能是这样的。
Json::Value min;
Json::Value event;
event["x"] = 10;
event["y"] = 20;
min["Cords"] = event;



// Output to see the result

cout<<min.toStyledString()

不可能在Json :: Value事件中完成吗?我不想单独打印它,因为我已经包含了其他数据到事件中,并将其作为整体打印。 - JJ Jones

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接