C++ Json库的简单使用


Json是什么?

  • json 是一种轻量级的文本数据交换格式;
  • json 独立于语言、平台,使用java script语法来描述对象;
  • json 解析器和json库对多种不同语言均提供了支持;
  • json (JavaScript Object Notation) 指的是javascript对象表示方法.

Json选择哪个比较好?

Json有很多版本,选择哪个比较好呢?这里推荐使用 nlohmann/json ,不需要编译,不需要配置环境,只需要一个头文件json.h

源文件下载:https://github.com/nlohmann/json

Json如何使用?

Json如何使用,有哪些操作规范?详细内容可参考https://github.com/nlohmann/json,这里只给出简单的测试用例。

//jsontest.h
#pragma once
#ifndef _JSONTEST_H
#define _JSONTEST_H
#include <iostream>
#include <fstream>
#include <iomanip>
#include "json.h"

using json = nlohmann::json;
using namespace std;

class JsonTest
{
public:
    JsonTest(const char *jsfilename = "odbc_test_case_config.json");
    ~JsonTest();
    void printTest();
private:
    const char *m_jsfilename;
};

#endif // _JSONTEST_H

//jsontest.cpp
JsonTest::JsonTest(const char *jsfilename)
    : m_jsfilename(jsfilename)
{
}

JsonTest::~JsonTest()
{
}

void JsonTest::printTest()
{
    //通过流的形式从.json文件取数据,并打印输出
    std::ifstream i(m_jsfilename);
    nlohmann::json j;
    i >> j;
    cout << j << endl;

    //以下内容可以不用看了,自己编程时用到的,供以后参阅用的。直接跳过到main.cpp
    int count = 1;
    string caseName = "Case_" + to_string(count);
    json js = j[caseName];
    
    cout << js["Results"][0]["Column_1"]["DataType"] << endl;
    string tmp = "Column_" + to_string(0);
    cout << js["Results"][0][tmp]["DataType"] << endl;
    if (js["Results"][0][tmp]["DataType"]=="INT")
    {
        cout << "int" << endl;
    }
    for (int i = 0; i < js["ResultColumns"]; i++)
    {
        string tmp1 = "Column_" + to_string(i);
        cout << js["Results"][0][tmp1]["Name"] << endl;
        
        if (js["Results"][0][tmp1]["DataType"] == "INT")
        {
            for (int j = 0; j < js["ResultRows"]; j++)
            {
                int value = js["Results"][j][tmp1]["Value"].get<int>();
                cout << value << endl;
            }
        }
        else if (js["Results"][0][tmp1]["DataType"] == "STRING")
        {
            for (int j = 0; j < js["ResultRows"]; j++)
            {
                string value = js["Results"][j][tmp1]["Value"].get<string>();
                cout << value << endl;
            }
        }
    }
}

//main.cpp
#include "JsonTest.h"
int main()
{
    //_STACKTRACE_begin_;
    
    JsonTest jt;
    jt.printTest(); //Json test.
    
    // _STACKTRACE_end_;
    system("pause");
    return 0;
}
发布了88 篇原创文章 · 获赞 16 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/WHEgqing/article/details/104540466