c++ jsoncpp 解析json

 jsoncpp 解析json

1、下载 : git clone https://github.com/open-source-parsers/jsoncpp.git

2、cmake 编译 、 vs打开生成。    

3、代码示例

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

using namespace std;

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int ReadJsonFromFile(const char* filename)
{
    Json::Reader reader;// 解析json用Json::Reader   
    Json::Value root; // Json::Value是一种很重要的类型,可以代表任意类型。如int, string, object, array         

    std::ifstream is;
    is.open(filename, std::ios::binary);

    ofstream outfile;
    outfile.open("./111.txt");
    if (reader.parse(is, root, false))
    {
        if (root["Registration"].isArray())
        {
            int fsize = root["Registration"].size();  // 得到"files"的数组个数  
            for (int i = 0; i < fsize; ++i)  // 遍历数组  
            {
                Json::Value val_position = root["Registration"][i]["position"];
                int val_position_size = val_position.size();
                if (val_position_size == 3)
                {
                    float x = val_position[0].asFloat();
                    float y = val_position[1].asFloat();
                    float z = val_position[2].asFloat();

                    outfile << x << " "<< y << " " << z << std::endl;
                }
                
                Json::Value val_eulerangle = root["Registration"][i]["eulerangle"];
                int val_eulerangle_size = val_eulerangle.size();
                if (val_eulerangle_size == 3)
                {
                    float x = val_eulerangle[0].asFloat();
                    float y = val_eulerangle[1].asFloat();
                    float z = val_eulerangle[2].asFloat();

                    outfile << x << " " << y << " " << z << " "<< 0.0 << std::endl;
                }
            }

        }        
    }
    is.close();
    outfile.close();

    return 0;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int main()
{
    ReadJsonFromFile("./panorama.json");

    return 0;
}
原文地址:https://www.cnblogs.com/lovebay/p/13497735.html