【问题标题】:Appending an array to a Json Value in C++在 C++ 中将数组附加到 Json 值
【发布时间】:2020-05-01 18:11:48
【问题描述】:

我知道如果我有一些整数“a”和“b”,我可以将它们附加到 Json 中的值:

Value root;
Value v = root["int"];
int a = 1;
int b = 2;
v.append(a);
v.append(b);

生成的 Json 文件:

"int": 
  [
    1,
    2
  ]

但是还有一种方法可以附加整个数组吗?也许是这样的:

Value root;
Value v = root["arrays"];
int a[3] = {1,2,3};
int b[3] = {4,5,6};
v.append(a);
v.append(b);

我正在尝试让生成的 Json 文件看起来像:

"arrays": 
  [
    [1, 2, 3],
    [4, 5, 6]
  ]

但是,Json 只是附加了指针地址值,读作“真”:

"arrays": 
  [
    true,
    true
  ]

【问题讨论】:

  • 您正在寻找.extend() 方法
  • 第二个代码的结果是什么?
  • 是的,extend() 正是我想要的,但我在 jsoncpp (github.com/open-source-parsers/jsoncpp) 中找不到。我认为 copy() 没有帮助,因为我仍然无法将该数组数据正确地放入 Json 文件中。
  • Rithik:最后一个盒子是我得到的。
  • hyde: range-for 很接近,但它只是转储两个没有结构的数组的所有值,如下所示: "arrays": [ 1, 2, 3, 4, 5, 6 ]

标签: c++ arrays json jsoncpp


【解决方案1】:

明确的方法是将 range-for 与 temp Value 一起使用。

Value root;
Value v = root["arrays"];
int a[3] = {1,2,3};
int b[3] = {4,5,6};

Value tmp;
for(auto i : a) { tmp.append(i); }
v.append(tmp);

tmp = Value{}; // reset
for(auto i : b) { tmp.append(i); }
v.append(tmp)

一个可能的帮助模板函数来很好地包装它:

template<typename RANGE>
Value rangeToValue(RANGE src) {
    Value result;
    for (const auto &value : src) {
        result.append(value);
    }
    return result;
}

那么这应该可以工作:

v.append(rangeToValue(a)); v.append(rangeToValue(b));

【讨论】:

  • 哎呀,是的!你是我今天最喜欢的人,海德。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-29
  • 1970-01-01
  • 1970-01-01
  • 2017-05-19
  • 2018-08-05
  • 1970-01-01
相关资源
最近更新 更多