江门网站推广多少钱,营销型企业网站建设步骤,企业做网站哪家好,wordpress评论内容不显示1、JSON-》string
操作步骤#xff1a; 1、在C中新建一个json对象并赋值#xff0c;然后将其转给char *data。 2、在使用 #include json.h 头文件时#xff0c;通常是使用第三方库 jsoncpp。由于它不是标准库的一部分#xff0c;所以需要从官网http://jsoncpp.sou…1、JSON-》string
操作步骤 1、在C中新建一个json对象并赋值然后将其转给char *data。 2、在使用 #include json.h 头文件时通常是使用第三方库 jsoncpp。由于它不是标准库的一部分所以需要从官网http://jsoncpp.sourceforge.net/下载相应的源码包并在编码时包含其头文件。
具体代码如下
#include json/json.h
#include iostream
#include json/json.h
int main() {// 新建 JSON 对象Json::Value root;// 给 JSON 对象添加键值对root[name] Alice;root[age] 25;// 将 JSON 对象转为字符串Json::StyledWriter writer;std::string json_str writer.write(root);// 将字符串转为 char*const char* data json_str.c_str();// 打印结果std::cout data std::endl;return 0;
}2、string-》JSON
操作步骤 1、使用 jsoncpp 库提供的 Json::Reader 类型来将 JSON 字符串转换为 Json::Value 类型的对象。 2、然后使用 operator[] 或者 get()函数来从 JSON 对象中读取特定键的值。
具体代码如下
#include iostream
#include json/json.h
int main() {// JSON字符串const char* data {\name\:\Alice\,\age\:25};// 将字符串转为 JSON 对象Json::Value root;Json::Reader reader;bool parsingSuccessful reader.parse(data, root);if (!parsingSuccessful) {std::cout 解析 JSON 失败 std::endl;return -1;}// 从 JSON 对象中读取特定键的值std::string name root[name].asString();int age root[age].asInt();// 打印结果std::cout 姓名 name std::endl;std::cout 年龄 age std::endl;return 0;
}此处需注意在读取 JSON 字符串之前应该使用 Json::Reader::parse() 函数检查字符串是否合法如果字符串不合法会导致程序崩溃。