JSON使用REST API进行分阶段

时间:2016-06-29 18:45:28

标签: c++ json rest

我正在尝试使用REST API&#39; s Json fuctionallity #include <cpprest/json.h>

在JSON文件中读取第二级

我需要从以下JSON获取名称字段:

{"desc":"","id":"57681f5dc4864c821cc73bfa","lists":[{"id":"576973346263056c88cfe845","name":"Board info"},{"id":"57681f5dc4864c821cc73bfb","name":"Misc"},{"id":"576978294972d812e4a91580","name":"thing"},{"id":"57681fdc228443c3306cc762","name":"thing2"},{"id":"5768200b1fbf41dd2c974052","name":"thing3"},{"id":"57681feb72ca90abb3afe170","name":"thingy"},{"id":"57681f5dc4864c821cc73bfc","name":"meep"},{"id":"57681f5dc4864c821cc73bfd","name":"BannedWordsPhrases"},{"id":"57681fba60fdfbf576abaece","name":"Errors"}],"name":"READER"}

(让我们调用这个文件JSON1) 我可以获得JSON1 [&#34;列表&#34;]但不能获得JSON1 [&#34;列表&#34;] [&#34;名称&#34;]。

这是我的代码:

#include "cpprest/json.h" //how I am importing stuff
...

typedef web::json::value JsonValue; //all of these are being uses
typedef web::json::value::value_type JsonValueType;
typedef std::wstring String;
typedef std::wstringstream StringStream;

using namespace utility;
using namespace web;
using namespace web::http;
using namespace web::http::client;
using namespace concurrency::streams;
...
int main() 
{ 
...
web::json::value J1 = web::json::value::parse(S);
web::json::value &J2 = web::json::value::parse(S1);
output(J2);
wfstream _file("jsonFile.json");
_file >> obj;
wcout << obj[L"lists"][L"name"]; // the broken line
cout << endl;
}

所有的功能和变量都有效且正确,它不会[L"name"][L"lists"]

我做错了什么?

1 个答案:

答案 0 :(得分:0)

注意:我的回答可能有误,如果您可以发布wcout << obj[L"lists"];的输出会有所帮助。此外,我假设你正在努力获得&#34; name&#34;如在&#34;董事会信息&#34;和&#34; Mics&#34;而不是&#34; READER&#34;。我假设wcout << obj[L"lists"];的输出是:

[{"id":"576973346263056c88cfe845","name":"Board info"},{"id":"57681f5dc4864c821cc73bfb","name":"Misc"},{"id":"576978294972d812e4a91580","name":"thing"},{"id":"57681fdc228443c3306cc762","name":"thing2"},{"id":"5768200b1fbf41dd2c974052","name":"thing3"},{"id":"57681feb72ca90abb3afe170","name":"thingy"},{"id":"57681f5dc4864c821cc73bfc","name":"meep"},{"id":"57681f5dc4864c821cc73bfd","name":"BannedWordsPhrases"},{"id":"57681fba60fdfbf576abaece","name":"Errors"}]

建议的答案obj[L"lists"];在这种情况下返回9个JSON对象的列表(如上所列)。您可以通过索引(0-8)访问这些JSON对象。例如,根据cpprestsdkobj[L"lists"][0];obj[L"lists"].at(0);应返回{"id":"576973346263056c88cfe845","name":"Board info"}

从那里你可以得到这个名字,例如:

obj[L"lists"][0][L"name"]应该返回Board info