我在使用 CPP REST SDK 的 JSON 类时遇到了问题。我不知道什么时候使用json::value,json::object和json::array。尤其是后两者看起来很像。的用法json::array对我来说也很不直观。最后,我想将 JSON 写入文件或至少写入 stdcout,以便我可以检查它是否正确。
使用 json-spirit 对我来说更容易,但是因为我想稍后发出 REST 请求,所以我想我会省掉字符串/wstring 的疯狂并使用 CPP REST SDK 的 json 类。
我想要实现的是一个像这样的 JSON 文件:
{
"foo-list" : [
{
"bar" : "value1",
"bob" : "value2"
}
]
}
Run Code Online (Sandbox Code Playgroud)
这是我试过的代码:
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;
Run Code Online (Sandbox Code Playgroud)
我真的需要这个额外的计数器变量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"));
Run Code Online (Sandbox Code Playgroud)
如果你想创建列表,比如bobList,你真的需要使用一些迭代器变量。否则你只会得到一堆单独的变量。
输出到控制台使用
cout << output.serialize().c_str();
Run Code Online (Sandbox Code Playgroud)
最后,这将导致
{
"foo-list":{
"bar":"value1",
"bob":"value2",
"bobList":[
"bobValue1",
"bobValue1",
"bobValue1"
]
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6871 次 |
| 最近记录: |