C++ 读取JSON CMakeLists

1、安装JSONCPP
CMakeLists

find_package(PkgConfig REQUIRED)
pkg_check_modules(JSONCPP jsoncpp)
include_directories(${JSONCPP_LIBRARIES})

add_executable(test1 point_show.cpp )

target_link_libraries(test1 ${JSONCPP_LIBRARIES} )

2、vscode里格式化显示json
安装JSON TOOLs插件
在这里插入图片描述

用vscode打开json文件,右键,选择“Format Document”

3、

JSON 文件
{
    "objects": [
        {
            "className": "Static",
            "position": {
                "x": 20.6775,
                "y": -1.64219,
                "z": 0.0651855
            },
            "rotation": {
                "pitch": 0,
                "roll": 0,
                "yaw": -0.0449259
            },
            "dimension": {
                "width": 0.463667,
                "height": 0.661766,
                "length": 0.464346
            },
            "score": 0.765948
        },
        {
            "className": "Car",
            "position": {
                "x": 9.03711,
                "y": 0.33086,
                "z": 0.437012
            },
            "rotation": {
                "pitch": 0,
                "roll": 0,
                "yaw": -3.12493
            },
            "dimension": {
                "width": 1.84011,
                "height": 1.61482,
                "length": 4.30554
            },
            "score": 0.761542
        }
 
  ]
}
C++ 文件
#include<iostream>
#include<fstream>
#include <json/json.h>
#include<string>
using namespace std;
int main(){
    ifstream jj;
    jj.open("/home/liao/PCL/result/1634335202100000.json",ios::binary);

    Json::Reader reader;
    Json::Value root;
    
    if(reader.parse(jj,root)){
        //int x=root["objects"][0]["position"][x].asInt();
        double x=stod(root["objects"][0]["position"]["y"].asString()); //float 或double类型,需要先转为string类型
        cout<<x<<endl;
        cout<<root["objects"][1]["position"]["x"].asInt()<<endl;
        cout<<root["objects"].size()<<endl;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44594953/article/details/123921901