【问题标题】:How do I make a jsoncpp array?如何制作 jsoncpp 数组?
【发布时间】:2018-01-22 10:07:06
【问题描述】:

我坚持使用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";

编辑:
我想在活动中全部打印出来。
我不想单独打印电线。

【问题讨论】:

标签: c++ arrays json jsoncpp


【解决方案1】:

需要使用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 如果我必须将它放入一个无效的函数中,最佳实践是什么?现在它说在'{'令牌之前不允许函数定义
  • 将coord的定义移到正在使用它的函数之外
  • 按预期工作!非常感谢您的帮助!
【解决方案2】:

可能是这样的

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 事件中不可能做到吗?不知何故?我不想单独打印它,因为我已经将其他数据包含到事件中并作为一个整体打印。
猜你喜欢
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-02
  • 1970-01-01
  • 1970-01-01
  • 2011-06-24
  • 1970-01-01
相关资源
最近更新 更多