C++中JSON与string格式互转

本文介绍了如何在C++中使用jsoncpp库进行JSON对象的创建、字符串化和从字符串解析的过程,包括新建JSON对象、添加键值对,以及验证和读取JSON字符串中的数据。
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值