C++中JSON与string格式互转

1、JSON-》string

操作步骤:

1、在C++中新建一个json对象并赋值,然后将其转给char *data。

2、在使用 #include 头文件时,通常是使用第三方库 jsoncpp。由于它不是标准库的一部分,所以需要从官网http://jsoncpp.sourceforge.net/下载相应的源码包,并在编码时包含其头文件。

具体代码如下:

#include #include #include 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 #include 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() 函数检查字符串是否合法,如果字符串不合法会导致程序崩溃。