您的位置:首页 > Web前端 > JavaScript

jsoncpp的读写操作

2015-07-05 10:46 603 查看
代码如下

#include <fstream>
#include <cassert>
#include <string>
#include <iostream>

#include "json/json.h"

#pragma comment(lib, "lib_json.lib")

using namespace std;

int main()
{
{
//读操作[{"name" : "xiaoy", "age" :17} , {"name" : "xiaot", "age" : 20}]
ifstream ifs;
ifs.open("f:\\test.json");
assert(ifs.is_open());

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

if (!reader.parse(ifs, root, false))
{
return -1;
}

string name;
int age;
int size = root.size();
for (int i = 0; i < size; i++)
{
name = root[i]["name"].asString();
age = root[i]["age"].asInt();

cout << name << " " << age << endl;
}
}

{
//写操作[{"age":100,"name":"hello world"}]
Json::Value root;
Json::FastWriter writer;
Json::Value person;

person["name"] = "hello, world";
person["age"] = 100;
root.append(person);

string json_file = writer.write(root);

ofstream ofs;
ofs.open("f:\\test.json");
assert(ofs.is_open());

ofs << json_file;
}

{
//读操作{"name" : "小楼一夜听春雨","age" : 27}
ifstream ifs;
ifs.open("f:\\test.json");
assert(ifs.is_open());

Json::Reader reader;
Json::Value root;
if (!reader.parse(ifs, root, false))
{
return -1;
}

string name = root["name"].asString();
int age = root["age"].asInt();

cout << name << " " << age << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: