美文网首页
VS2015下JSON文件的读写

VS2015下JSON文件的读写

作者: AllenWang0217 | 来源:发表于2020-02-27 23:49 被阅读0次

    生成库文件

    我这里使用的是jsoncpp

    1. 源码可从git上直接下载:
      jsoncpp
    2. 切换到VS可用节点
      最新的源码中没找到可用的VS工程文件,我这里切到了18年的一个节点,commitId:768e31
    3. 加载工程
      运行:makefiles/msvc2010/jsoncpp.sln,会出现三个Project:jsontest, lib_json, test_lib_json
    4. 运行库设置为多线程

      选择中间的lib_json项目,右键 -> 属性 -> C/C++ -> 代码生成 -> 运行库 -> 多线程DLL(/MDd) 设置多线程.png
    5. 重新生成

      分别在Debug和Release版本下重新生成 重新生成.png 成功后在makefiles\msvc2010下生成两个文件夹 重新生成.png
    6. 保存lib文件
      在include平行的目录下新建一个lib文件夹,将上一步生成的两个文件只保留lib库拷出来
    ├─include
    │  └─json
    ├─lib
    │  ├─Debug
    │  │  └─lib_json.lib
    │  └─Release
    │      └─lib_json.lib
    ├─makefiles
    │  ├─msvc2010
    │  │  ├─Debug
    │  │  │  └─lib_json.tlog
    │  │  └─Release
    │  │      └─lib_json.tlog
    │  └─vs71
    

    配置VS2015

    配置方式与gtest基本一致

    1. 新建一个vs工程,Win32控制台应用程序----TestJson
    2. 添加头文件的搜索路径 添加头文件的搜索路径.png
    3. 添加lib库的搜索路径。

      这个路径就是我们之前创建的lib文件夹(这里以Debug为例) 添加lib库的搜索路径.png
    4. 添加链接依赖项,lib_json.lib 添加链接依赖项.png

      这样VS就配置完成啦

    读写JSON文件

    JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式。
    其组织形式与C++中的map一样,是通过key-value对来组织的,key是任意一个唯一字符串,value可以是bool,int,string 或者嵌套的一个json。具体可以参考官方网站
    本次一个这样的Json为例:

    {
        "customer" : "BigCo",
        "performances" : 
        [
            {
                "audience" : 55,
                "playID" : "hamlet"
            },
            {
                "audience" : 35,
                "playID" : "as-like"
            },
            {
                "audience" : 40,
                "playID" : "othello"
            }
        ]
    }
    

    进行C++的读写

    #include <json/json.h>
    #include <fstream>
    #include <iostream>
    #include <string>
    #include <memory>
    #include <sstream>
    
    using namespace std;
    
    void fillStuff(Json::Value& root)
    {
        Json::Value performances, performance;
        root["customer"] = "BigCo";
        performance["playID"] = "hamlet";
        performance["audience"] = 55;
        performances[0] = performance;
        performance["playID"] = "as-like";
        performance["audience"] = 35;
        performances[1] = performance;
        performance["playID"] = "othello";
        performance["audience"] = 40;
        performances[2] = performance;
        root["performances"] = performances;
    }
    
    void createJson1()
    {
        cout << "========" << "creat json invoices.json" << "========" << endl;
        Json::Value root;
        fillStuff(root); // 填写JSON内容
    
        // 将JSON内容(缩进格式)输出到文件
        ofstream os;
        os.open("invoices.json");
        Json::StreamWriterBuilder writerBuilder;
        std::unique_ptr<Json::StreamWriter> writer(writerBuilder.newStreamWriter());
        writer->write(root, &os); //从writer中读取并存到文件流
        os.close();
        // 将JSON内容(缩进格式)显示到终端
        writer->write(root, &cout); //从writer中读取并存到输出流
        cout << endl;
    }
    
    void createJson2()
    {
        cout << "========" << "creat json invoices.json" << "========" << endl;
        Json::Value root;
        fillStuff(root); // 填写JSON内容
    
        // 将JSON内容(缩进格式)输出到文件
        ofstream os;
        os.open("invoices.json");
        os << root.toStyledString(); //转换为json格式并存到文件流
        os.close();
    }
    
    void printJson(Json::Value& root)
    {
        cout << "customer: " << root["customer"].asString() << endl;
        cout << "performances:" << endl;
        for (int i = 0; i < 3; i++)
        {
            cout << "  {" << "playID:" << root["performances"][i]["playID"].asString() << "; ";
            cout << "   " << "audience:" << root["performances"][i]["audience"].asInt() << "}," << endl;
        }
    }
    
    bool parseJson1()
    {// 直接解析文件流
        cout << "========" << "read json invoices.json" << "========" << endl;
        // 以二进制形式读取json文件内容
        ifstream is("invoices.json", ios::binary);
        if (!is.is_open())
        {
            cout << "open json file failed." << endl;
            return false;
        }
    
        bool res;
        JSONCPP_STRING errs;
        Json::Value root;
        Json::CharReaderBuilder readerBuilder;
    
        res = Json::parseFromStream(readerBuilder, is, &root, &errs);
        if (!res || !errs.empty()) {
            cout << "parseJson err. " << errs << endl;
            is.close();
            return false;
        }
        printJson(root);
        is.close();
        return true;
    }
    
    bool parseJson2()
    { // 通过CharReader解析string
        // 以二进制形式读取json文件内容
        ifstream is("invoices.json", ios::binary);
    
        if (!is.is_open())
        {
            cout << "open json file failed." << endl;
            return false;
        }
        // 转换成string
        ostringstream os;
        os << is.rdbuf();
        string info = os.str();
        os.clear();
        os.str("");
    
        if (info.empty())
            return false;
    
        bool res;
        JSONCPP_STRING errs;
        Json::Value root;
        Json::CharReaderBuilder crbuilder;
    
        std::unique_ptr<Json::CharReader> const jsonReader(crbuilder.newCharReader());
        res = jsonReader->parse(info.c_str(), info.c_str() + info.length(), &root, &errs);
        if (!res || !errs.empty()) {
            cout << "parseJson err. " << errs << endl;
            return false;
        }
        printJson(root);
        is.close();
        return true;
    }
    
    int main()
    {
        createJson1();
    //    createJson2();
        parseJson1();
     //   parseJson2();
        return 0;
    }
    

    最终打印到终端的应该是这样子的

    ========creat json invoices.json========
    {
            "customer" : "BigCo",
            "performances" :
            [
                    {
                            "audience" : 55,
                            "playID" : "hamlet"
                    },
                    {
                            "audience" : 35,
                            "playID" : "as-like"
                    },
                    {
                            "audience" : 40,
                            "playID" : "othello"
                    }
            ]
    }
    ========read json invoices.json========
    customer: BigCo
    performances:
      {playID:hamlet;    audience:55},
      {playID:as-like;    audience:35},
      {playID:othello;    audience:40},
    

    这样就成功啦

    相关文章

      网友评论

          本文标题:VS2015下JSON文件的读写

          本文链接:https://www.haomeiwen.com/subject/fdogchtx.html