JSONCPP学习笔记

基本使用

使用jsoncpp库解析、修改、打印JSON串

源文件
$ cat main.cpp
#include <iostream>
#include "json/json.h"

using namespace std;

const char *style = "{ \
    \"encoding\" : \"UTF-8\", \
    \"plug-ins\" : [ \
        \"python\", \
        \"c++\", \
        \"ruby\" \
        ], \
    \"indent\" : {\"length\" : 3, \"use_space\": true } \
}";

int main()
{
    Json::Reader reader;
    Json::Value root;
    if (!reader.parse(style, root))
    {
        cout << "parse fails." << endl;
        return -1;
    }

    // 基础数据的读取
    std::string encoding = root.get("encoding", "GBK" ).asString();
    cout << "encoding : " << encoding << endl;
    // 列表数据的读取
    const Json::Value plugins = root["plug-ins"];
    cout << "plug-ins : [ ";
    for ( int index = 0; index < plugins.size(); ++index )
    {
        cout << plugins[index].asString();
        if (index != plugins.size())
            cout << ", ";
    }
    cout << " ]" << endl;
    // 对象数据的读取和修改
    root["indent"]["length"] = 4;
    root["indent"]["use_space"] = false;

    // 打印修改后的JSON串
    cout << "Json after modify:" << endl;
    Json::StyledStreamWriter output;
    output.write(std::cout, root);
}

转载于:https://www.cnblogs.com/silvermagic/p/9087635.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值