jsoncpp讲解,让你秒会jsoncpp

1.干货,常见api和解析

1.创建一个json对象
使用 Json::Value 对象来创建 JSON 数据
然后使用 Json::FastWriter 或 Json::StyledWriter 来生成字符串
//构建json格式字符串,注意构建出来是倒序的
void createJson(string &s)
{
    Value value;
    value["sex"] = "man";
    value["score"] = 100;
    value["is_student"] = true;

    FastWriter writer;
    s = writer.write(value);
}

2.如何将接收到的json格式字符串转化为json对象并且解析
/*
asString():返回字符串类型的数据。
asInt():返回整数类型的数据。
asBool():返回布尔值类型的数据。
asDouble():返回双精度浮点类型的数据。
size():返回数组或对象的大小。
*/
    Reader read;
    Value value;
    //解析成功会返回为0
    if(read.parse(s,value))
    {
        cout << "解析成功" << endl;
        cout << "name:" << value["name"].asString() << endl;
        cout << "age:" << value["age"].asInt() << endl;
    }

3.遍历 JSON 对象或数组
Json::Value arr = root["items"];
for (Json::ArrayIndex i = 0; i < arr.size(); i++) {
    std::cout << "Item " << i << ": " << arr[i].asString() << std::endl;
}

4.isMember() 来检查一个键是否存在于 JSON 对象中。
if (root.isMember("name")) {
    std::cout << "Name: " << root["name"].asString() << std::endl;
} else {
    std::cout << "Name key not found!" << std::endl;
}

5.数组操作:向 JSON 数组中添加元素
Json::Value arr;
arr.append("first item");
arr.append(123);
arr.append(true);

二.代码案例

// #include <iostream>
// #include <jsoncpp/json/json.h>
// using namespace std;
// using namespace Json;

// //将传进来的json格式字符串解析为json对象并解析出来
// void readJson(string &s)
// {
//     Reader read;
//     Value value;
//     //解析成功会返回为0
//     if(read.parse(s,value))
//     {
//         cout << "解析成功" << endl;
//         cout << "name:" << value["name"].asString() << endl;
//         cout << "age:" << value["age"].asInt() << endl;
//     }
// }
// //构建json格式字符串,注意构建出来是倒序的
// void createJson(string &s)
// {
//     Value value;
//     value["sex"] = "man";
//     value["score"] = 100;
//     value["is_student"] = true;

//     FastWriter writer;
//     s = writer.write(value);
// }

// int main()
// {
//     string json = R"({"name":"zbz","age":18})";
//     readJson(json);
//     string json2;
//     createJson(json2);
//     cout << "json2:" << json2 << endl;
//     return 0;
// }
#include <jsoncpp/json/json.h>
#include <iostream>
using namespace std;
using namespace Json;

void readJson(string &s)
{
    Reader read;
    Value value;
    if(read.parse(s,value))
    {
        cout << "解析成功" << endl;
        cout << "name:" << value["name"].isString() << endl;
        cout << "age:" << value["age"].isInt() << endl;
    }
}

void createJson(string &s)
{
    Value value;
    FastWriter writer;
    value["name"] = "Dale";
    value["age"] = 18;
    s = writer.write(&value);
}

int main()
{
    string s  = R"({"name":"Bob","age":20})";
    readJson(s); 
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值