c++解析json文件: Rapidjson

json文件用来当配置文件很好用,很轻便。但是试过好几个c++的json库,有些编译特别麻烦。

Rapidjson的使用很简单,添加几个头文件就行了,而且跨平台,速度快。

JSON文件:

[
	{ 
		"bank_name" : "BOA",
    	"chain_num":123, 
    	"servers":[
    		{
    			"ip" : "127.0.0.1",
    			"port" : 1111
    		},
    		{
    			"ip" : "127.0.0.1",
    			"port" : 2222
    		}
    	] 
	},

	{ 
		"bank_name" : "CITIBANK",
    	"chain_num":789, 
    	"servers":[
    		{
    			"ip" : "127.0.0.1",
    			"port" : 3333
    		},
    		{
    			"ip" : "127.0.0.1",
    			"port" : 4444
    		}
    	]
	}
]

解析代码:

#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/filestream.h" 
#include 
#include 
#include 

using namespace rapidjson;
using namespace std;

int main()
{
    FILE *fp = fopen("t2.json", "r");
    FileStream is(fp);

    Document bank;
    bank.ParseStream<0>(is);

    if (bank.HasParseError())
    {
        printf("GetParseError %s\n", bank.GetParseError());
    }

    for (unsigned int i = 0; i < bank.Size(); ++i)
    {
        const Value & cur_bank = bank[i];
        cout <<"BANK # "<< i+1 <


你可能感兴趣的:(C++)