string类型的字符串转json
时间: 2023-11-11 14:00:02 浏览: 122
可以使用第三方库,如jsoncpp或者rapidjson来将string类型的字符串转换为json格式。以下是使用jsoncpp的示例代码:
```c++
#include <iostream>
#include <json/json.h>
int main() {
std::string str = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
Json::Value root;
Json::CharReaderBuilder builder;
Json::CharReader* reader = builder.newCharReader();
std::string errors;
bool parsingSuccessful = reader->parse(str.c_str(), str.c_str() + str.size(), &root, &errors);
delete reader;
if (parsingSuccessful) {
std::cout << "Name: " << root["name"].asString() << std::endl;
std::cout << "Age: " << root["age"].asInt() << std::endl;
std::cout << "City: " << root["city"].asString() << std::endl;
} else {
std::cout << "Parsing error: " << errors << std::endl;
}
return 0;
}
```
阅读全文