/*
test1.json文件 [数组]
[
 [2.0,5.6],
 [5.2,9.6]
]


*/

/*
test2.json文件  [对象]
{
	"backupIP": "localhost",
	"code": 0,
	"discovery": "http://127.0.0.1/api",
	"port": "8000",
	"priorIP": "127.0.0.1"
}

*/

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include "jsoncpp\json\json.h"
using namespace std;

//读取文件中的对象
bool readFileJsonObj(const char *_Filename)
{
	if (_Filename == NULL)
	{
		std::cout << "_Filename || pSampledata == null erro!\n";
		return false;
	}

	Json::Reader reader;
	Json::Value root;

	//从文件中读取,保证当前文件有data.json文件
	std::ifstream in(_Filename, ios::binary);

	if( !in.is_open() )  
	{ 
		std::cout << "Error open: " <<_Filename<<std::endl; 
		return false; 
	}

	/*

	{
	"backupIP": "localhost",
	"code": 0,
	"discovery": "http://127.0.0.1/api",
	"port": "8000",
	"priorIP": "127.0.0.1"
	}

	*/
	if(reader.parse(in,root))
	{

		int nCode = root.get("code", "").asInt();
		std::cout<<nCode<<" , ";
		std::cout<<root.get("priorIP", "").asString()<<" , ";
		std::cout<<	root.get("backupIP", "").asString()<<" , ";
		std::cout<<root.get("port", "").asString()<<" , ";
		std::cout<<root.get("discovery", "").asString()<<std::endl;


	}
	in.close();
	return true;
}

//从文件中读取JSON  数组
bool readFileJson(const char *_Filename)
{
	if (_Filename == NULL)
	{
		std::cout << "_Filename || pSampledata == null erro!\n";
		return false;
	}

	Json::Reader reader;
	Json::Value root;

	//从文件中读取,保证当前文件有data.json文件
	std::ifstream in(_Filename, ios::binary);

	if( !in.is_open() )  
	{ 
		std::cout << "Error open: " <<_Filename<<std::endl; 
		return false; 
	}

	/*
	json
	[
	[2.0,5.6],
	[5.2,9.6]
	]

	*/

	int nTatolSize = 0;
	if(reader.parse(in,root))
	{

		int ns = root.size();
		//读取数组信息
		for(unsigned int i = 0; i < ns; i++)
		{
			Json::Value tmp = root[i];
			nTatolSize += tmp.size();  

		}
		std::cout<<"nTatolSize : "<<nTatolSize <<"\n";
		for(unsigned int i = 0; i < ns; i++)
		{
			Json::Value tmp = root[i];
			int image_size = tmp.size();  

			for(int j = 0; j < image_size; ++j)  
			{  
				float fvalue= tmp[j].asFloat(); 
				std::cout<<"value : "<<fvalue <<" , ";
			} 
			std::cout<<"\n";
		}

	}
	in.close();
	return true;
}

int _tmain(int argc, _TCHAR* argv[])
{
	readFileJson("test1.json");
	readFileJsonObj("test2.json");
	return 0;
}

 

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐