c++读写json

一、json文件格式详解

https://www.cnblogs.com/hwtblog/p/8483573.html

JSON建构于两种结构:

(1)“名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。

(2)值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)。

二、代码示例

 	size_t pls_num;
    size_t area_num;
    string pls_file = "/home/dmh/program/test/cmake_test/output/CameraPLSParam.json";//读取文件的路径
    //1.创建读取文件的流,判断ifstream是否读取成功
    ifstream pls_in(pls_file);
    if(!pls_in)
    {
        cout << pls_file << "load fail!" << std::endl;
    }
    //2.创建json对象,通过ifstream推流后判断是否创建json对象成功
    nlohmann::json pls_json;
    pls_in >> pls_json;
    if(!pls_json.is_object())
    {
        cout << "pls_json is not obj" << std::endl;
    }
    //3.通过判断对象是否为null,确保程序安全。
    if(pls_json.at("3dpls").is_null())
    {
        cout << "3dpls is null" << std::endl;
    }
    //4.通过at访问具体名称对应的数值,数组可以通过循环遍历。
    pls_num = pls_json.at("3dpls").size();
    cout << "pls_num:" << pls_num << std::endl;
    for(int i = 0; i < pls_num; i++)
    {
        area_num = pls_json.at("3dpls").at(i).at("PlsArea").size();
        std::cout << "PlsArea:" << i << " have " << area_num << " pls area" << std::endl;
        for(int j =0; j < area_num; j++)
        {

            cout << "AreaId:" << pls_json.at("3dpls").at(i).at("PlsArea").at(j).at("AreaId") << std::endl;
        }
    }
    if(pls_json.at("version").is_null())
    {
        cout << "version is null" << std::endl;
    }
    cout << "version:" << pls_json.at("version") << std::endl;
    //5.关闭推流
    pls_in.close();

你可能感兴趣的:(C++基础,c++,json,开发语言)