1

我正在尝试使用以下方式写入 json 的 C++ REST API。

json::value resp;
std::vector<Portfolio> portfolio;
// Populate portfolio
this->PortfolioList(usrStr, pwdStr, portfolio);
std::vector<Portfolio>::iterator it;
for (it = portfolio.begin(); it != portfolio.end(); it++)
{
    char costBuff[40]; _itoa_s(it->GetTotalCost(), costBuff, 10);
    char qtyBuff[40]; _itoa_s(it->GetQuantity(), qtyBuff, 10);

    json::value portfolioEntry;
    portfolioEntry[U("username")] = json::value::string(utility::conversions::to_string_t(it->GetUserName()));
    portfolioEntry[U("stockCode")] = json::value::string(utility::conversions::to_string_t(it->GetStockCode()));
    portfolioEntry[U("quantity")] = json::value::string(utility::conversions::to_string_t(qtyBuff));
    portfolioEntry[U("totalcost")] = json::value::string(utility::conversions::to_string_t(costBuff));

    resp[utility::conversions::to_string_t(it->GetStockCode())] = portfolioEntry;
}

为此,我得到如下输出

{
 "11002":{"quantity":11002,"totalcost":"272","username":"arunavk"},
 "11003":{"quantity":11003,"totalcost":"18700","username":"arunavk"},
 "11004":{"quantity":11004,"totalcost":"760","username":"arunavk"},
 "11005":{"quantity":11005,"totalcost":"32","username":"arunavk"}
}

现在,在接收端,我尝试如下阅读

for (int i = 0; i < size; i++)
{
    table->elementAt(i, 0)->addWidget(new Wt::WText(this->response[i][0].as_string()));
    table->elementAt(i, 1)->addWidget(new Wt::WText(this->response[i][1].as_string()));
    table->elementAt(i, 2)->addWidget(new Wt::WText(this->response[i][2].as_string()));
    table->elementAt(i, 3)->addWidget(new Wt::WText(this->response[i][3].as_string()));
} 

但它失败了。我错过了什么?

请原谅我,我是这个 REST、Casablanca 和 JSON 的新手

4

1 回答 1

2

从JSON的角度来看以下

{
 "11002":{"quantity":11002,"totalcost":"272","username":"arunavk"},
 "11003":{"quantity":11003,"totalcost":"18700","username":"arunavk"},
 "11004":{"quantity":11004,"totalcost":"760","username":"arunavk"},
 "11005":{"quantity":11005,"totalcost":"32","username":"arunavk"}
}

是具有属性“11002”,...“11005”的 java 脚本对象,不是数组。因此,如果要获取属性值,则必须使用属性名称:

this->response["11002"]["quantity"]

因为当您使用整数索引时, json::value::operator [] 假设您要访问数组元素。这是详细信息https://microsoft.github.io/cpprestsdk/classweb_1_1json_1_1value.html#a56c751a1c22d14b85b7f41a724100e22

更新

如果您不知道收到的对象的属性,可以调用 value::as_object 方法(https://microsoft.github.io/cpprestsdk/classweb_1_1json_1_1value.html#a732030bdee11c2f054299a0fb148df0e)来获取 JSON 对象,之后您可以使用特定的使用开始和结束迭代器遍历字段的接口:https ://microsoft.github.io/cpprestsdk/classweb_1_1json_1_1object.html#details

于 2016-08-10T08:40:07.320 回答