#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include "json/json.h"
using namespace std;
struct SStudent
{
int id; //编号
string name; //姓名
int age; //年龄
string address; //地址
};
typedef vector<SStudent> SeqSStudent;
/*
void fromJs( SStudent& stu, std::string js )
{
Json::Value json;
Json::Reader reader;
reader.parse( js.c_str(), json );
stu.id = json["id"].asInt();
stu.name = json["name"].asString();
stu.age = json["age"].asInt();
stu.address = json["address"].asString();
}
*/
void fromJs( SStudent& stu, Json::Value jv)
{
stu.id = jv["id"].asInt();
stu.name = jv["name"].asString();
stu.age = jv["age"].asInt();
stu.address = jv["address"].asString();
}
void loadFile(const std::string& file, SeqSStudent& seq)
{
Json::Value json;
Json::Reader reader;
ifstream ifs ( file.c_str() );
reader.parse( ifs, json );
SStudent stu;
for( Json::Value::UInt i = 0; i < json.size(); ++ i )
{
fromJs( stu, json[i] );
seq.push_back( stu );
}
}
int main(int argc, char* argv[])
{
SeqSStudent seqStu;
loadFile("student.json", seqStu);
cout << "begin print" << endl;
for(SeqSStudent::const_iterator cit = seqStu.begin(); cit != seqStu.end(); ++cit)
{
cout << "id:" << cit->id << "\tname: " << cit->name << "\tage: " << cit->age << "\tAddress: " << cit->address << endl;;
}
cout << "end print" << endl;
return 0;
}
转载于:https://my.oschina.net/jianchaopeng/blog/280397