JSON for Modern C++库快速上手使用示例

                           JSON for Modern C++库快速上手使用示例

     JSON for Modern C++是JSON解析工具,功能完善、使用方便。仅需包含一个头文件“json.hpp”,没有外部依赖,也不需额外的安装、编译、链接工作,适合快速上手开发。

 

一、库github地址,可先下载json.hpp

https://github.com/nlohmann/json/blob/develop/include/nlohmann/json.hpp

 

二、测试源码

json_test.cpp


#include <iostream>
#include "json.hpp"

using namespace std;

using json_t = nlohmann::json;

static void case0()
{
    json_t j = {
        {"age", 23},
        {"name", "tanxiaohai"},
        {"jobs", {"superhero", "neighborhood"}},
        {"gear", {"suits", "2099"}}
    };
    cout<<j.dump(2)<<endl;
}

static void case1()
{
    json_t j;
    j["age"] = 23;
    j["name"] = "spiderman";
    j["gear"]["suits"] = "2099";
    j["jobs"] = {"superhero", "neighborhood"};

    vector<int> v = {1, 2, 3};
    j["numbers"] = v;

    map<string, int> m = {{"one", 1}, {"two", 2}};
    j["kv"] = m;

    //cout<<j.dump()<<endl;
    cout<<j.dump(2)<<endl;
}


static void case2()
{
    string str = R"({
        "name" : "naruto",
        "age"  : 15,
        "married" : false
    })";

    auto j = json_t::parse(str);

    assert(j["age"] == 15);
    assert(j["name"] == "naruto");

    cout<<j.dump(2)<<endl;
}


static void case3()
{
    auto txt = "bad:data"s;

    try
    {
        auto j = json_t::parse(txt);
    }
    catch(std::exception &e)
    {
        cout<<e.what()<<endl;
    }
}

int main()
{
    case0();
    // case1();
    // case2();
    // case3();
    return 0;
}

三、编译测试

g++ json_test.cpp -std=c++14 -o json_test

./json_test

欢迎转载请注明出处:海漩涡

http://blog.csdn.net/tanhuifang520

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值