Json和Xml相比有个最大的优势,基于字符串。xml必须与文件相关,而json只是字符串(当然也提供了与文件相关的操作)。
Let's say it from my code:
#include <json/json.h> //解压后找到目录 vs71,用vs打开然后生成解决方案,本程序直接在jsontest.cpp中改写的
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const string g_file = "json.c"; //原本以为vs打开该文件后会对json格式字符串做一个format,结果和记事本打开一样,不如xml条理清晰
// 此处两个结构体并没有用到,他们的目的只是让我们看清楚json字符串的格式
struct Address
{
string name; //街道名
int number; //街道号
};
struct Student
{
int no; //学好
string name; //名字
Address addr; //家庭地址
};
void Write()
{
Json::Value root; //根(如果树的根一样)
int no[] = { 2008, 2010, 2013 };
string name[] = { "sumos", "fly away", "sun"};
string name2[] = { "西湖路", "东湖路", "中南海" };
int number[] = { 101, 202, 303 };
for(int k = 0; k < 3; k++)
{
Json::Value person, addr;
person["no"] = Json::Value(no[k]);
person["name"] = Json::Value(name[k]);
addr["name"] = Json::Value(name2[k]);
addr["number"] = Json::Value(number[k]);
person["address"] = addr;
root.append(person);
}
Json::FastWriter writer; // FastWriter没有Encode
ofstream out;
out.open(g_file);
if(out.is_open())
{
out<< writer.write(root);
out.close();
}
}
void Read()
{
ifstream in;
in.open(g_file);
if( ! in.is_open() )
return;
Json::Reader reader;
Json::Value root;
bool r = reader.parse(in,root);
if( ! r )
{
in.close();
return;
}
int n = root.size();
for(int k = 0; k < n; k++)
{
Json::Value person = root[k];
cout<< person["no"].asInt() << person["name"].asString() <<endl;
Json::Value addr = person["address"];
cout<< addr["name"].asString() << addr["number"].asInt() <<endl <<endl;
}
in.close();
}
int main(int,char**)
{
Read();
system("pause");
return 0;
}
好吧,感觉不需要什么注释就可以很轻松的明白了。