您的位置:首页 > 编程语言 > C语言/C++

C++解析JSON格式(JSONCpp库)

2015-09-06 19:45 531 查看
RoutePointFormatPtr结构(CommonFormat.h):

typedef struct _RoutePointFormat
{
_RoutePointFormat()
{
}

double	X;
double	Y;
double	Z;
}RoutePointFormat, *RoutePointFormatPtr;


Functions.h

//Some functions.

#ifndef	_FUNCTIONS_H_
#define  _FUNCTIONS_H_

#include "json/json.h"
#ifdef _DEBUG
#pragma  comment(lib, "json_vc71_libmtd.lib")
#else
#pragma comment(lib, "json_vc71_libmt.lib")
#endif // _DEBUG

#include <vector>
#include <string>
#include "CommonFormat.h"
std::vector<RoutePointFormatPtr> ReadJsonFromFile(const std::string &fileName);

#endif //_FUNCTIONS_H_

Functions.cpp

#include "Functions.h"
#include <iostream>
#include <fstream>

std::vector<RoutePointFormatPtr> ReadJsonFromFile( const std::string &fileName )
{
std::vector<RoutePointFormatPtr> routePoint;

Json::Reader reader;// 解析json用Json::Reader
Json::Value root; // Json::Value是一种很重要的类型,可以代表任意类型。如int, string, object, array

std::ifstream is;
is.open (fileName, std::ios::binary );
if (reader.parse(is, root, false))
{
long file_size = root["wayPoints"].size();  // 得到数组个数
for(long i = 0; i < file_size; ++i)  // 遍历数组
{
RoutePointFormatPtr pRoutePoint = new RoutePointFormat;
Json::Value val_wayPoints = root["wayPoints"][i];
pRoutePoint->X = val_wayPoints["X"].asDouble();
pRoutePoint->Y = val_wayPoints["Y"].asDouble();
pRoutePoint->Z = val_wayPoints["Z"].asDouble();
routePoint.push_back(pRoutePoint);
}
}
is.close();

return routePoint;
}
测试Json文件:

{
"wayPoints":[
{"X":0,"Y":1,"Z":2},
{"X":0,"Y":2,"Z":1},
{"X":1,"Y":2,"Z":0}
]
}


参考:

点击打开链接 /article/6956147.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: