jsoncpp库使用实例

jsoncpp与json

  • json是什么

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式。它是一种文本格式。它实际上是一种独立于编程语言的数据格式,几乎所有现代编程语言都支持解析和生成JSON数据。

JSON采用键值对的形式来表示数据,其中键是字符串,值可以是数字、字符串、布尔值、数组、对象(也就是嵌套的键值对)或者null。这种简单和通用的格式使得JSON在数据交换、配置文件、API通信等领域被广泛应用

  • jsoncpp是什么

JsonCpp是一个用于C++的开源JSON解析库,它能够轻松地处理JSON数据。

地址:https://github.com/open-source-parsers/jsoncpp

实例

#include <iostream>
#include <fstream>
#include <json/json.h>


int main() {
    // 1. 定义JSON文件名
    std::string filename = "example.json";

    // 2. 创建JsonCpp的根对象
    Json::Value root;

    // 3. 读取JSON文件
    std::ifstream file(filename, std::ifstream::binary);
    if (!file) {
        std::cout << "Failed to open the JSON file: " << filename << std::endl;
        return 1;
    }

    Json::CharReaderBuilder reader;
    std::string errors;
    bool parsingSuccessful = Json::parseFromStream(reader, file, &root, &errors);
    file.close();

    if (!parsingSuccessful) {
        std::cout << "Failed to parse the JSON file: " << filename << std::endl;
        return 1;
    }

    // 4. 获取值
    std::string name = root["name"].asString();
    int age = root["age"].asInt();
    bool isStudent = root["is_student"].asBool();
    std::string city = root["address"]["city"].asString();
    std::string zipcode = root["address"]["zipcode"].asString();

    // 5. 获取数组
    Json::Value hobbies = root["hobbies"];
    for (const auto& hobby : hobbies) {
        std::cout << "Hobby: " << hobby.asString() << std::endl;
    }

    // 6. 输出获取的值
    std::cout << "Name: " << name << std::endl;
    std::cout << "Age: " << age << std::endl;
    std::cout << "Is Student: " << std::boolalpha << isStudent << std::endl;
    std::cout << "City: " << city << std::endl;
    std::cout << "Zipcode: " << zipcode << std::endl;

    return 0;
}

输出

Hobby: reading
Hobby: swimming
Hobby: coding
Name: John Doe
Age: 30
Is Student: true
City: New York
Zipcode: 10001
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值