栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

json.hpp解析和遍历json数据

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

json.hpp解析和遍历json数据

下面的代码可以演示典型的读取操作,记得在获取json的值时,一定要判断find() != end(),否则如果直接访问还可以,返回NULL,如果用string或int变量去接收,就会错误退出了。

#include 
#include "json.hpp"
using namespace std;

using namespace nlohmann;
int main(int argc, char const *argv[])
{
    json data = json::parse("{"code": 0, "msg": "OK"}");
    if (data.is_discarded()) {
        cout << "data is not valid json" << endl;
        return -1;
    }
    if (data.find("code") == data.end()) {
        cout << "no code in json" << endl;
        return -1;
    }

    for (auto item: data.items()) {
        cout << item.key() << ": " << item.value()  << endl;
    }

    const unsigned short &code = data["code"]; // 这里可以是任何数值类型,short,int,longlong包括unsigned
    cout << "code: " << code << endl;

    data = json::parse("[1, 3, 5, 7, 9]");
    for (int i = 0; i < data.size(); i++) {
        cout << i << ": " << data[i] << endl;
    }

    return 0;
}

下面的文章中包含更全面的操作:http://www.zyiz.net/tech/detail-250507.html

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/954346.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号