用JsonCpp從一個未知Json文件遍歷解析所有的結點與值

用JsonCpp從一個未知Json文件遍歷解析所有的結點與值

#include <iostream>
#include"json.h"
#include <string>
#include <fstream>
#include <sstream>
#include <string>
#include <Windows.h>
#include <map>
using namespace std;
typedef Json::Writer JsonWriter;
typedef Json::Reader JsonReader;
typedef Json::Value  JsonValue;

int myfloor = 0;
string str;
void analysejson(Json::Value v)
{
	if (v.type() == Json::stringValue)
	{
		 
		cout << v.asString() << endl;
		myfloor++;
		cout << myfloor << endl;
		myfloor--;
		return;
	}
	else if (v.type() == Json::realValue)
	{
		cout << v.asString() << endl;
		myfloor++;
		cout << myfloor << endl;
		myfloor--;
		return;
	}
	else if (v.type() == Json::uintValue)
	{
		cout << v.asString() << endl;
		myfloor++;
		cout << myfloor << endl;
		myfloor--;
		return;
	}
	else if ((v.type() == Json::intValue))
	{
		cout << v.asString() << endl;
		myfloor++;
		cout << myfloor << endl;
		myfloor--;
		return;
	}
	else if (v.type() == Json::arrayValue)
	{
		cout << endl;

		int cnt2 = v.size();
		for (int i = 0; i <cnt2; i++)
		{
			analysejson(v[i]);
		}
		myfloor++;
		cout << myfloor << endl;
		myfloor--;
		return;
	}
	JsonValue::Members mem = v.getMemberNames();
	for (auto iter = mem.begin(); iter != mem.end(); iter++)
	{
		
		str = *iter + ":";
		if (v[*iter].type() == Json::objectValue)
		{
			myfloor++;
			cout << str << endl;
			cout << myfloor << endl;
			analysejson(v[*iter]);
		}
		else if (v[*iter].type() == Json::arrayValue)
		{
			cout << str << endl;
			int cnt = v[*iter].size();
			myfloor++;
			cout << myfloor << endl;
			for (int i = 0; i <cnt; i++)
			{
				analysejson(v[*iter][i]);
			}
		}/*
		else if (v[*iter].type() == Json::stringValue)
		{
			str = str + v[*iter].asString();
			cout << str << endl;
			myfloor++;
			cout << myfloor << endl;
		}
		else if (v[*iter].type() == Json::realValue)
		{  
			str = str + v[*iter].asString();
			cout << str << endl;
			myfloor++;
			cout << myfloor << endl;
		}
		else if (v[*iter].type() == Json::uintValue)
		{
			str = str + v[*iter].asString();
			cout << str << endl;
			myfloor++;
			cout << myfloor << endl;
		}*/
		else
		{
			string temp = str + v[*iter].asString();
			cout << temp << endl;
			myfloor++;
			cout << myfloor << endl;
		}
		myfloor--;
	}
	return;
}


int main()
{
	ifstream myfile("E:\\xxxx.Json");
	string temp;
	string json_string;
	if (!myfile.is_open())
	{
		cout << "未成功打開文件" << endl;
	}
	while (getline(myfile, temp))
	{
		json_string += temp;
	}
	myfile.close();
	cout << json_string.c_str() << endl;
	Json::Reader reader;
	Json::Value root;
	cout << json_string.c_str() << endl;
	if (reader.parse(json_string, root))  // reader將json_string字符串解析到root,root將包含json_string裏所有子元素     
	{
		analysejson(root);
	}
	system("pause");
 	return 0;
}


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