我正在使用C++读取JSON值
Json::Reader reader
值被存储在Json :: Value root
中。
这个root包含"age"和"id",我想将root ["age"]转换为整数。
我尝试使用.str()将其转换为字符串,但无法获取。
有什么建议吗?
在 jsoncpp
中,他们为 Json::Value
对象提供了辅助方法。你只需调用值上的 asInt()
方法进行转换。
int ageAsInt = root["age"].asInt()
x.asString().asInt()
没有意义。std::string 没有 asInt() 方法。 - Nathaniel Jonesstd::stoi( string )
这个例子来自http://en.cppreference.com/w/cpp/string/basic_string/stol。
#include <iostream>
#include <string>
int main()
{
std::string test = "45";
int myint = std::stoi(test);
std::cout << myint << '\n';
}
如果无法直接转换为整数,先将其转换为字符串,然后再转换为整数
string age = root["age"].asString();
int age2 = std::stoi(age);