Linux下json文件读写

参考:C/C++之读写JSON数据_c++读取json文件-优快云博客

1、安装json库

sudo apt-get install libjsoncpp-dev

2、CMakeLists.txt

cmake_minimum_required(VERSION 2.8)

project(test-json)
add_executable(${PROJECT_NAME} "main.cpp")

target_link_libraries(${PROJECT_NAME} -ljsoncpp)

3、main.cpp

#include <iostream>
#include <fstream>
#include <jsoncpp/json/value.h>
#include <jsoncpp/json/reader.h>
#include <jsoncpp/json/writer.h>

using namespace std;

void readStrProJson();
void readFromFile();
void writeFileJson();

int main()
{
    readStrProJson();
    readFromFile();
    writeFileJson();

    return 0;
}

void readStrProJson()
{
    string strValue = "{"
                          "\"name\":\"Derozan\","
                          "\"major\":["
                          "{"
                            "\"Player\":\"EDG player\""
                          "},"
                          "{"
                            "\"Player\":\"Basketball Player\""
                          "}]"
                      "}";
    Json::Reader reader;
    Json::Value value;
    if (reader.parse(strValue, value))
    {
        string out = value["name"].asString();
        cout << out << endl;
        const Json::Value arrayObj = value["major"];
        for (unsigned int i = 0; i < arrayObj.size(); i++)
        {
            out = arrayObj[i]["Player"].asString();
            cout << out<<endl;
        }
    }
}

void readFromFile() {
   Json::Reader reader;
   Json::Value root;
   const char* path = "./test.json";
   std::ifstream infile(path);
   if(reader.parse(infile, root)) {
    //读取根节点信息
        std::string name = root["name"].asString();
        int age = root["age"].asInt();
        std::string sex = root["sex"].asString();
        std::cout << "My name is " << name << std::endl;
        std::cout << "I'm " << age << " years old" << std::endl;
        std::cout << "I'm a " << sex << std::endl;

        //读取子节点信息
        std::string friend_name = root["friends"]["friend_name"].asString();
        int friend_age = root["friends"]["friend_age"].asInt();
        std::string friend_sex = root["friends"]["friend_sex"].asString();
        std::cout << "friend's name is " << friend_name << std::endl;
        std::cout << "friend's sex is "<<friend_sex << std::endl;
        std::cout << "friend is " << friend_age << " years old" << std::endl;

        //读取数组信息
        std::cout << "my hobby:" << std::endl;
        for (unsigned int i = 0; i < root["hobby"].size(); i++)
        {
            std::string ach = root["hobby"][i].asString();
            std::cout << ach << '\t';
        }
        std::cout << std::endl;
        std::cout << "Reading Success!" << std::endl;
   }
}

void writeFileJson()
{
    //根节点
    Json::Value root;

    //根节点属性
    root["name"] = Json::Value("Derozan");
    root["age"] = Json::Value(27);
    root["sex"] = Json::Value("man");

    //子节点
    Json::Value friends;

    //子节点属性
    friends["friend_name"] = Json::Value("Alen");
    friends["friend_age"] = Json::Value(35);
    friends["friend_sex"] = Json::Value("man");

    //子节点挂到根节点上
    root["friends"] = Json::Value(friends);

    //数组形式
    root["hobby"].append("Basketball");
    root["hobby"].append("Swimming");
    root["hobby"].append("game");

    //直接输出
    //cout << "FastWriter:" << endl;
    //Json::FastWriter fw;
    //cout << fw.write(root) << endl << endl;

    //缩进输出
    std::cout << "StyledWriter:" << std::endl;
    Json::StyledWriter sw;
    std::cout << sw.write(root) << std::endl << std::endl;

    //输出到文件
    std::ofstream os;
    const char* path = "./testwrite.json";
    os.open(path, std::ios::out | std::ios::app);
    if (!os.is_open())
        std::cout << "error:can not find or create the file which named \" demo.json\"." << std::endl;
    os << sw.write(root);
    os.close();
}


4、终端输出

Derozan
EDG player
Basketball Player
My name is Alen
I'm 25 years old
I'm a women
friend's name is Derozan
friend's sex is man
friend is 25 years old
my hobby:
basket	women	sleep	
Reading Success!
StyledWriter:
{
   "age" : 27,
   "friends" : {
      "friend_age" : 35,
      "friend_name" : "Alen",
      "friend_sex" : "man"
   },
   "hobby" : [ "Basketball", "Swimming", "game" ],
   "name" : "Derozan",
   "sex" : "man"
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值