gpt4 book ai didi

json - CPP REST SDK JSON - 如何创建带数组的 JSON 并写入文件

转载 作者:行者123 更新时间:2023-12-05 01:44:50 26 4
gpt4 key购买 nike

我在使用 CPP REST SDK 的 JSON 类时遇到问题。我不知道何时使用 json::valuejson::objectjson::array。尤其是后两者,看起来很像。此外,json::array 的用法对我来说相当不直观。最后,我想将 JSON 写入文件或至少写入 stdcout,以便检查它是否正确。

使用 json-spirit 对我来说更容易,但由于我想稍后发出 REST 请求,我想我应该省去 string/wstring 的疯狂并使用 CPP REST SDK 的 json 类。

我想要实现的是一个像这样的 JSON 文件:

{
"foo-list" : [
{
"bar" : "value1",
"bob" : "value2"
}
]
}

这是我试过的代码:

json::value arr;
int i{0};
for(auto& thing : things)
{
json::value obj;
obj[L"bar"] = json::value::string(thing.first);
obj[L"bob"] = json::value::string(thing.second);
arr[i++] = obj;
}
json::value result;
result[L"foo-list"] = arr;

我真的需要这个额外的计数器变量 i 吗?显得比较不雅观。使用 json::array/json::object 会让事情变得更好吗?以及如何将我的 JSON 写入文件?

最佳答案

这可以帮助您:

json::value output;
output[L"foo-list"][L"bar"] = json::value::string(utility::conversions::to_utf16string("value1"));
output[L"foo-list"][L"bob"] = json::value::string(utility::conversions::to_utf16string("value2"));

output[L"foo-list"][L"bobList"][0] = json::value::string(utility::conversions::to_utf16string("bobValue1"));
output[L"foo-list"][L"bobList"][1] = json::value::string(utility::conversions::to_utf16string("bobValue1"));
output[L"foo-list"][L"bobList"][2] = json::value::string(utility::conversions::to_utf16string("bobValue1"));

如果你想创建列表,比如 bobList,你确实需要使用一些迭代器变量。否则你只会得到一堆单独的变量。

用于输出到控制台使用

cout << output.serialize().c_str();

最后,这将导致

{
"foo-list":{
"bar":"value1",
"bob":"value2",
"bobList":[
"bobValue1",
"bobValue1",
"bobValue1"
]
}
}

关于json - CPP REST SDK JSON - 如何创建带数组的 JSON 并写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44597525/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com