Android中C++如何读写json文件

4 篇文章 0 订阅

我们需要在json文件中记录一下总数,文件格式如下:
[{"total_count":0,"total_count1":0,"total_count2":0,"total_count3":0,"total_count4":0}]

目录

1. Android.bp中新增

2. 头文件添加

3. 向json文件写入数据

4. 读取json文件内容


1. Android.bp中新增

    static_libs: [
        "libjsoncpp",
    ], 

2. 头文件添加

#include <json/json.h>


3. 向json文件写入数据

    long long totalCount = 0;
    long long totalCount2 = 0;
    long long totalCount3 = 0;
    long long totalCount4 = 0;
    fstream fileStream;
    fileStream.open("/sdcard/test.json", ios::out | ios::in);
    if (!fileStream.is_open()) {
        return;
    }
    Json::Value root;
    Json::Value item;
    item["total_count"] = Json::Int64(totalCount);
    item["total_count2"] = Json::Int64(totalCount2);
    item["total_count3"] = Json::Int64(total_count3);
    item["total_count4"] = Json::Int64(total_count4);
    root.append(item);
    Json::FastWriter wb; 
    string str = wb.write(root);
    fileStream << str;
    fileStream.flush();

写完之后,/sdcard/test.json文件内容如下:
[{"total_count":0,"total_count1":0,"total_count2":0,"total_count3":0,"total_count4":0}]


4. 读取json文件内容

    fileStream.open("/sdcard/test.json", ios::out | ios::in);
    if (!fileStream.is_open()) {
        return;
    }
    isTotalStreamValid = true;
    char buffer[1024];
    fileStream.getline(buffer, sizeof(buffer));
    Json::Reader reader;
    Json::Value root;
    if (!reader.parse(buffer, root)) {
        return;
    }
    totalCount = root[0]["total_count"].asInt64();
    totalCount2 = root[0]["total_count2"].asInt64();
    totalCount3 = root[0]["total_count3"].asInt64();
    totalCount4 = root[0]["total_count4"].asInt64();


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值