zoukankan      html  css  js  c++  java
  • json for modern c++(nlohmann json)使用小计

    前言

    一开始使用jsoncpp,但是jsoncpp已经不更新了,nlohmann还在更新,并且jsoncpp做过一次大的版本升级,导致api不兼容,以前使用过的工程代码不能很好的升级到新的版本,并且jsoncpp是多个文件支持,使用的时候我编译成了lib,nlohmann是一个头文件,更方便。

    nlohmann使用c++11的新功能,更多的c++方法,使用起来更方便。并且nlohmann在调试的时候,可以看到数据结构,这个太有用了,而jsoncpp,只能通过内部的方法导出string。

    由于各种原因把jsoncpp切换到nlohmann,在nlohmann使用时有一些需要注意的。不过大部分注意事项作者已经写到github上了 https://github.com/nlohmann/json

    由于作者是基于json标准的,我fork了一个分支,增加了一些易用性的不是在json标准中的功能

    https://github.com/studywithallofyou/json

    1.

    nlohmann支持隐式转换,但是不要使用,因为行为不确定

    看下面的例子及输出结果

    long long lnum = 327221437;
    nlohmann::json a;
    a["num1"] = 327220625;
    nlohmann::json b;
    b["num2"] = 900000;
    if (lnum - a["num1"] > b["num2"])
    {
        cout << lnum << endl;
        cout << a["num1"] << endl;
        cout << b["num2"] << endl;
        cout << lnum - a["num1"] << endl;
        cout << lnum - a["num1"].get<long long>() << endl;
    }
    /*
    327221437
    327220625
    900000
    327221292
    812
    */

    lnum - a["num1"] > b["num2"]并不成立,但是进来了,如果写成lnum - a["num1"].get<long long>() > b["num2"].get<long long>()就没问题

    2.

    在调用json::parse(iter.begin(), iter.end())的时候需要注意,作者也说了,是[iter.begin(), iter.end()),左闭右开的,所以如果是一个数组保存了json字符串,那么就是a, a+len,而不是a, a+len-1

    3.

    nlohmann::json::parse如果是非法的json会直接丢一个异常,可以通过nlohmann::json::accept判断是否合法

  • 相关阅读:
    Android之Margin和Padding属性及支持的长度单位
    java jvm eclipse 性能调优
    spring aop 内部方法调用事务不生效问题解决
    服务器 获取用户 真实ip
    Nginx gzip配置
    全局唯一的支付和订单id生成算法
    spring aop 方法增加日志记录
    linux cp复制文件 直接覆盖
    Twitter分布式自增ID算法snowflake原理解析
    nginx 命令
  • 原文地址:https://www.cnblogs.com/studywithallofyou/p/11276613.html
Copyright © 2011-2022 走看看