System:Ubuntu18.04
VS version:1.61.2
1. 安装jsoncpp库
sudo apt-get install libjsoncpp-dev libjsoncpp1 libjsoncpp-doc
2. 修改VS编译的json文件
先在VS界面左侧找到.vscode
文件夹,然后在里面有四个json文件,如下图所示:
然后打开其中的tasks.json
,如下图所示:
中间args
的参数里面只有-g
和-o
,这里需要加多一个-l
,添加jsoncpp的库,改完后,如下图所示:
当然,要在VS里面调试ROS的代码,还需要配合修改可执行文件的地址,这个在我另一篇blog有写,可以参考,点击这里打开
3. 添加头文件
最后只需要在要编译的文件里面添加jsoncpp的头文件就可以了:
在cpp文件中加入头文件
#include <jsoncpp/json/json.h>
4.测试代码
先弄一个测试读取的json文件,以waypoints.json
命名
{
"type" : "point",
"array" : [
{"x":1,"y":21,"z":31,"w":0.1},
{"x":2,"y":22,"z":32,"w":0.2},
{"x":3,"y":23,"z":33,"w":0.3},
{"x":4,"y":24,"z":34,"w":0.4}
]
}
再写一个叫test_json.cpp
的文件
#include <iostream>
#include <cstdlib>
#include <math.h>
#include <fstream>
#include <string>
#include <jsoncpp/json/json.h>
using namespace std;
int main(int argc, char **argv) {
Json::Value root;
Json::Reader reader;
Json::FastWriter fwriter;
Json::StyledWriter swriter;
Json::Value array;
std::ifstream ifs("/home/will/Documents/json_test/waypoints.json");//open file example.json
if(!reader.parse(ifs, root)){
// fail to parse
cout << "fail to parse" << endl;
}
else{
// success
array = root["array"];
std::cout<<"Num: " << array.size()<<endl;
for (int index = 0; index < array.size(); ++index) { // Iterates over the sequence elements.
//cout << "Element " << index << " in array: " << array[index].asString() << endl;
Json::Value position = array[index];
cout << "Element: " << index << " x: " << (position["x"]).asFloat() <<" y:"<< position["y"].asFloat() <<" z:"<< position["z"].asFloat()<<" w:"<< position["w"].asFloat()<< endl;
position["x"]=Json::Value(1234);
array[index] = position;
}
}
root["array"] = array;
std::string str = fwriter.write(array);
std::ofstream ofs("/home/will/Documents/json_test/example_fast_writer.json");
ofs << str;
ofs.close();
str = swriter.write(root);
ofs.open("/home/will/Documents/json_test/example_styled_writer.json");
ofs << str;
ofs.close();
return 0;
}
编译加运行:
Ctrl+shift+B
F5
输出:
Num: 4
Element: 0 x: 1 y:21 z:31 w:0.1
Element: 1 x: 2 y:22 z:32 w:0.2
Element: 2 x: 3 y:23 z:33 w:0.3
Element: 3 x: 4 y:24 z:34 w:0.4
同时在对应的路径下还有两个json文件,分别是两种格式的,Fast和style,一个快速度读写,一个是按标准格式
Reference
- ROS 使用C++ jsoncpp库 读写保存json.json 文件
https://blog.csdn.net/qq_29796781/article/details/80853300?spm=1001.2101.3001.6650.6&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-6.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-6.no_search_link&utm_relevant_index=10 - ROS中配置jsoncpp:
http://www.cleartechfei.com/2019/03/rosjsoncpp/