C++解析Json格式

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <memory.h>
#include <fstream>
#include "json11.hpp"

using namespace std;
using namespace json11;

void test1()
{
    Json obj = Json::object{
        {"china", "beijing"},
        {"key1", true},
        {"key2", Json::array{1,2,3}},
    };
    string s = obj.dump();
    cout << s << endl;
    cout << obj["china"].string_value() << endl;
    cout << obj["key1"].bool_value() << endl;
    cout << "[";
    for(auto item : obj["key2"].array_items())
    //for(int i =0; i< obj["key2"].array_items().size(); i++){}
    {
        cout << item.int_value() << ",";
    }
    cout << "]" << endl;
}

void test2()
{
    Json::array ar1 = {1,2,3};
    Json::array ar2 = {1,2,3};
    Json::array ar3 = {1,2,3};
    Json::array ar = {ar1,ar2,ar3};
    Json obj = Json(ar);
    string s = obj.dump();
    cout << s << endl;
}


void test3()
{
	Json obj = Json::array { Json::object{ { "k", "v" } },
                             Json::object{ { "m", "n" } } };
	std::string str = obj[0]["k"].string_value();
	std::cout << str << std::endl;
}

void test4()
{
    FILE* fin = fopen("data.json", "r");
    string s;
    char buf[100];
    while(!feof(fin))
    {
        memset(buf, 0, 100);
        fgets(buf, 100, fin);
        s += buf;
    }
    //ifstream in("data.json");
    ifstream in;
    in.open("data.json", ios::in);
    string buffer;
    while(!in.eof())
    {
        char line[100];
        in.getline(line, 100);
        buffer += line;
        cout << line << endl;
    }
    //cout << buffer << endl;
    fclose(fin);
    in.close();
}

int main()
{
    std::cout << "**************test1**************" << std::endl;
    test1();
    std::cout << "**************test2**************" << std::endl;
    test2();
    std::cout << "**************test3**************" << std::endl;
	test3();
    std::cout << "**************test4**************" << std::endl;
    test4();
	std::cout << "***************ok****************" << std::endl;
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章