jsoncpp学习笔记

jsoncpp


一. json基础

类型:
1. Json::Value为主要数据类型;
2. Json::Reader将文件流或字符串创解析到Json::Value中,主要使用parse函数;3. Json::Writer:与JsonReader相反,将Json::Value转换成字符串流等,Writer类是一个纯虚类,并不能直接使用。在此我们使用 Json::Writer 的子类:son::FastWriter(将数据写入一行,没有格式),Json::StyledWriter(按json格式化输出,易于阅读)


二. 解析json

1. 从内存解析json
void f() {
    Json::Value root;
    Json::Reader reader;

    char str[] = "{\"name\" : \"liushall\", \"age\" : 20, \
        \"files\" : [\"1.json\", \"2.json\"]}";
    if ( !reader.parse( str, root ) ) {
        cout << "parse error.\n";
        return -1;
    }

    cout << "name : " << root["name"].asString() << endl;
    cout << "age : " << root["age"].asInt() << endl;

    Json::Value files = root["files"];
    cout << "files : ";
    for( int i = 0; i < files.size(); i++ ) {
        cout << files[i].asString() << ' ';
    }
}

2. 从文件中解析json

提供的json文件:

{
    "name" : "liushall",
    "age" : 10;
}

代码:

void f() {
    Json::Reader reader;
    Json::Value root;

    ifstream ifs("test.json");

    if ( !reader.parse( ifs, root ) ) {
        cout << "parse error.\n";
        return -1;
    }

    cout << root["name"].asString() << endl;
    cout << root["age"].asInt() << endl;
}

三. 封装json

1. 简单json数据封装
void f() {
    Json::Value root;
    Json::StyledWriter writer;

    root["name"] = "liushall";
    root["age"] = 20;

    string str = writer.write( root );
    cout << str << endl;
}
2. 封装json数据——内嵌array的object
int main() {
    Json::Value root;
    Json::StyledWriter writer;

    root["name"] = "liushall";
    root["age"] = 20;
    root["msg"] = "linux";

    Json::Value files;
    files["haha"] = "1.cpp";
    files["ha"] = "2.cpp";

    root["files"] = files;
    string str = writer.write( root );
    cout << str << endl;
}
3. 封装json数据——内嵌object的array
void f() {
    Json::Value root;
    Json::StyledWriter writer;

    {
        Json::Value person; 
        person["name"] = "liushall";
        person["age"] = 100;
        root.append( person );
    }

    {
        Json::Value person; 
        person["name"] = "Kit";
        person["age"] = 89;
        root.append( person );
    }

    root.append( "a json note" );   

    string json_file = writer.write(root);
    cout << json_file << endl;
}

注意,不能直接用root[0] = person;,需要声明[]内数字的类型,即root[1U] = person,声明为unsigned类型。

参考:
https://www.cnblogs.com/tocy/p/json-intro_jsoncpp-lib.html
https://www.cnblogs.com/DswCnblog/p/6678708.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值