学习笔记 c++( C++ 操作 json 文件)

json_study.h 

/*
 * @Author: Li Chao 
 * @Date: 2020-11-07 16:50:38 
 * @Last Modified by: Li Chao
 * @Last Modified time: 2020-11-10 11:48:56
 */

#include <string>
#include <json/json.h>
#include <iostream>
#include <fstream>

using namespace std;

class JsonProc
{
public:

    JsonProc();
    ~JsonProc();
    void readStrJson();     //从字符串中读取JSON
    void readStrProJson();  //从字符串中读取JSON(内容复杂些)
    void readFileJson();    //从文件中读取JSON 
    void writeFileJson();   //将信息保存为JSON格式 
    
private:

};

json_study.cpp

/*
 * @Author: Li Chao 
 * @Date: 2020-11-10 11:28:18 
 * @Last Modified by: Li Chao
 * @Last Modified time: 2020-11-11 16:36:37
 */

#include "json_study.h"

JsonProc::JsonProc()
{

}

JsonProc::~JsonProc()
{
    
}

void JsonProc::readStrJson()
{
    /*定义一个字符串来保存如下json数据
    {
    "name" : "shuiyixin",
    "age" : "21",
    "sex" : "man"
    }*/
    const char* str = "{\"name\":\"lichao\",\"age\": 22,\"sex\":\"man\"}";

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

    //从字符串中读取数据  
    if(reader.parse(str, root))
    {
        string name = root["name"].asString();
        int age = root["age"].asInt();
        string sex = root["sex"].asString();
        cout<< name + "," << age << "," << sex <<endl;
    }
}

void JsonProc::readStrProJson()
{
/*
{
    "name":"lichao",
    "major":[
    {
        "AI":"MachineLearning"
    },
    {
        "AI":"DeepLearning"
    },
    {
        "AI":"ComputerVision"
    }]
}
*/
	string strValue = "{\"name\":\"lichao\",\"major\":[{\"AI\":\"MachineLearning\"},{\"AI\":\"DeepLearning\"},{\"AI\":\"ComputerVision\"}]}";
    Json::Reader reader;
    Json::Value root;

    if(reader.parse(strValue, root))
    {
        string name = root["name"].asString();
        cout<< name << endl;
        //const Json::Value arrayObj = root["major"];
        for(unsigned int i = 0; i < root["major"].size(); i++)
        {
            string AI = root["major"][i]["AI"].asString();
            cout<< AI <<endl;
        }
    }

}

void JsonProc::readFileJson()
{
    Json::Reader reader;
    Json::Value root;

/*
{
   "age" : 21,
   "friends" : {
      "friend_age" : 21,
      "friend_name" : "chengjing",
      "friend_sex" : "wuman"
   },
   "hobby" : [ "sing", "run", "Tai Chi" ],
   "name" : "lichao",
   "sex" : "man"
}*/
    //从文件中读取,保证当前文件有demo.json文件
    ifstream json_file("demo.json", ios::binary);
    if(!json_file.is_open())
    {
        cout<<"Error opening file"<<endl;
        return;
    }

    if(reader.parse(json_file, root))
    {
        //读取根节点信息
        string name = root["name"].asString();
        int age = root["age"].asInt();
        string sex = root["sex"].asString();

        cout<<"My name is "<<name<<endl;
        cout<<"I'm "<< age <<"years old"<<endl;
        cout<<"I'm a "<<sex<<endl;

        //读取子节点信息
        string friend_name = root["friends"]["friend_name"].asString();
        int friend_age = root["friends"]["friend_age"].asInt();
        string friend_sex = root["friends"]["friend_sex"].asString();

        cout<<"My friend's name is "<<friend_name<<endl;
        cout<<"My friend's "<< friend_age <<"years old"<<endl;
        cout<<"My friend's is "<<friend_sex<<endl;

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

        cout<< "Reading Complete!"<<endl;
    }
    else
    {
        cout<<"parse error\n"<<endl;
    }
    
    json_file.close();
}

void JsonProc::writeFileJson()
{
/*
{
   "age" : 21,
   "friends" : {
      "friend_age" : 21,
      "friend_name" : "chengjing",
      "friend_sex" : "wuman"
   },
   "hobby" : [ "sing", "run", "Tai Chi" ],
   "name" : "lichao",
   "sex" : "man"
}*/
    //根节点 
    Json::Value root;

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

    //子节点
    Json::Value friends;

    //子节点属性
    friends["friend_name"] = Json::Value("mengyao");
    friends["friends_age"] = Json::Value(18);
    friends["friends_sex"] = Json::Value("wuman");

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

    //数组形式
    root["hobby"].append("sing");
    root["hobby"].append("run");
    root["hobby"].append("Tai Chi");

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

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

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

 json_main.cpp

/*
 * @Author: Li Chao 
 * @Date: 2020-11-11 16:34:06 
 * @Last Modified by:   Li Chao 
 * @Last Modified time: 2020-11-11 16:34:06 
 */

#include "json_study.h"

int main(int agrc, char** argv)
{
    JsonProc* jsonproc = new JsonProc;
    jsonproc->readStrJson();
    cout<<"\n\n";
    jsonproc->readStrProJson();

    cout<<"\n\n";
    jsonproc->readFileJson();

    cout<<"\n\n";
    jsonproc->writeFileJson();    

    delete jsonproc;
    return 0;
}

 makefile

CC = g++
CFLAGS = -std=c++11
 
all: json_main.cpp  json_study.o 
	$(CC) $(CFLAGS) json_main.cpp  json_study.o -o json_exe -ljson

json_study.o: json_study.cpp json_study.h 
	$(CC) $(CFLAGS) -c json_study.cpp
 
clean:
	rm -f *.o json_exe 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值