C++使用JSON——JSON for Modern C++

本文详细介绍了一个由德国开发者nlohmann编写的JSON库——JSON for Modern C++的使用方法。该库仅包含一个json.hpp文件,遵循C++11标准,具有直观的语法和高效的内存管理特性。文章还提供了如何在C++项目中引入并使用该库的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

详解:https://blog.csdn.net/forrid/article/details/78867679
json for modern c++的使用:https://blog.csdn.net/fengxinlinux/article/details/71037244

JSON for Modern C++ 是德国大牛nlohmann写的:
https://github.com/nlohmann/json#projects-using-json-for-modern-c

特点

基本配置

1.将json.hpp复制到c++工程文件中
2. 在main.cpp文件中,添加以下代码

#include "json.hpp"
// 为方便起见,设置命名空间
using json = nlohmann::json;

3.编译
对于GCC和Clang编译器,可能出现以下问题:
Q1:C++出现to_string is not a member of std 或者 to_string was not declared in this scope的
A1:对于GCC和Clang编译器,需要打开c++11 支持
以codeblocks为例:
1)点击settings->complier,打开global compiler settings,在compiler flags中勾选Have g++ follow the C++11 ISO C++ language standard,点击ok,具体如下:
在这里插入图片描述
2)下载 mingw-to-string-gcc47.zip( http://tehsausage.com/mingw-to-string-gcc47.zip)
3)解压文件,将wchar.hstdio.h复制到codeblocks安装路径中的\mingw\include中,将它们替换掉;将os_defines.h复制到\mingw\lib\gcc\mingw32\4.x.x\include\c++\mingw32\bits中即可。

测试

1 使用iostream
#include <iostream>
#include <fstream>
#include "json.hpp"
using namespace std;
using json=nlohmann::json;
int main()
{

    json j;  //创建json类
    cin>>j;   //从cin读入json对象
    cout<<j;  //输出序列化的json
    return 0;
}

/*
输入:
{
  "pi": 3.141,
  "happy": true,
  "name": "Niels",
  "nothing": null,
  "answer": {
    "everything": 42
  },
  "list": [1, 0, 2],
  "object": {
    "currency": "USD",
    "value": 42.99
  }
}
输出:
{"answer":{"everything":42},"happy":true,"list":[1,0,2],"name":"Niels","nothing":null,"object":{"currency":"USD","value":42.99},"pi":3.141}
*/
2 使用fstream
 json j;  //创建json类
 std::ifstream i("file.json"); //可以读取txt、json等文件
 i>>j;
 cout<<j;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值