gpt4 book ai didi

C++ REST (Casablanca) - 读取 JSON 时失败

转载 作者:行者123 更新时间:2023-11-30 03:39:27 24 4
gpt4 key购买 nike

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

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 的新手

最佳答案

从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 对象,然后您可以使用特定的接口(interface)通过开始和结束迭代器遍历字段: https://microsoft.github.io/cpprestsdk/classweb_1_1json_1_1object.html#details

关于C++ REST (Casablanca) - 读取 JSON 时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38868033/

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