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

猜你喜欢

转载自blog.csdn.net/Star_ID/article/details/131834153