Skip to content

Latest commit

 

History

History
65 lines (45 loc) · 1.43 KB

File metadata and controls

65 lines (45 loc) · 1.43 KB

JSON 解析器

一个轻量级的 C++17 JSON 解析库。

功能特性

  • 支持从字符串或文件解析 JSON
  • 支持所有 JSON 类型:null、boolean、number、string、array、object
  • 简单直观的 API
  • 头文件形式的用法

项目结构

.
├── include/
│   ├── jsonparser.h      # 头文件
│   └── jsonparser.cpp    # 实现
└── test.cpp              # 测试程序

使用方法

#include "jsonread.h"

int main() {
    jsonread::JsonParser parser;
    
    // 从文件解析
    auto json = parser.parseFile("data.json");
    double value = json["key"].asNumber();
    
    // 从字符串解析
    auto json2 = parser.parse(R"({"name": "test", "value": 123})");
    std::string name = json2["name"].asString();
    
    // 访问嵌套值
    auto nested = json2["data"]["x"].asNumber();
    
    // 访问数组元素
    auto arrElement = json2["arr"][0].asNumber();
    
    return 0;
}

API

JsonValue

  • isNull(), isBool(), isNumber(), isString(), isArray(), isObject() - 类型检查
  • asBool(), asNumber(), asString(), asArray(), asObject() - 获取值
  • asInt(), asBoolOpt() - 可选类型转换
  • operator[] - 访问对象键或数组索引

JsonParser

  • parse(const std::string& jsonStr) - 解析 JSON 字符串
  • parseFile(const char* filePath) - 解析 JSON 文件

环境要求

  • C++17 兼容编译器
  • g++ 或 gcc