myReadJson.h:
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include "CJsonObject.hpp"
using namespace std;
using namespace neb;
class MyMap
{
public:
int a;
int b;
int c;
int parseJSON(CJsonObject oJson);
};
class Base_MyDevice{
public:
string name ;
int id;
vector<MyMap> ListMap;
int parseJSON(CJsonObject oJson);
};
class MyDevice :public Base_MyDevice {
public: MyDevice( ){};
public: MyDevice(string name, int id) {
this->name = name;
this->id = id;
}
}
class MyDeviceList {
public : vector<MyDevice> devicels;
MyDeviceList();
void read_JSon(string path);
}
myReadJson.cpp:
#include "srxdevice.h"
#include <fstream>
MyDeviceList:: MyDeviceList(){
read_JSon("C:\\Users\\Administration\\Desktop\\Text.json");
// read_JSon("Text.json");
}
int MyMap::parseJSON(CJsonObject je) {
je.Get("a", a);
je.Get("b", b);
je.Get("c", c);
return 0;
}
int Base_MyDevice::parseJSON(CJsonObject oJson) {
oJson.Get("name",name);
oJson.Get("id",id);
for(int n=0; n < oJson["lists"].GetArraySize(); n++){
MyMap m;
m.parseJSON(oJson["lists"][n]);
ListMap.push_back(m);
}
return 0;
}
//读取JSON文件
void MyDeviceList::read_JSon(string path)
{
ifstream t(path);
string str((istreambuf_iterator<char>(t)),istreambuf_iterator<char>());
string strValue;
CJsonObject oJson = CJsonObject(str);
for(int n=0; n < oJson.GetArraySize(); n++){
MyDevice m;
m.parseJSON(oJson[n]);
devicels.push_back(m);
}
// cout << Objson.ToFormattedString();
cout << "devicels.size()== " << devicels.size() << endl;
}
在main.cpp 中调用MyDeviceList() 方法 就能打印出来读到Text.json 的 数组长度
Text.json:示例
[
{
"name": "a1",
"id": 1,
"lists": [
{
"a" : 0,
"b": 0,
"c": 8
},
{
"a" : 1,
"b": 1,
"c": 7
}
]
},
{
"name": "b1",
"id": 2,
"lists": [
{
"a" : 0,
"b": 0,
"c": 8
},
{
"a" : 1,
"b": 1,
"c": 7
}
]
}
]