环境centos
在github上下载json相关包
然后将文件移入指定路径(看个人)
需要安装cmake
在该路径下创建如下路径 /build/release
然后在 /release跑cmake 编译整个项目(下载过来的文件)
最后再 make 一遍
找到静态库 我的静态库相对路径为 /build/release/src/lib_json
libjsoncpp.a
还需要配置头文件路径,导入json头文件
注意:不要下太新的json包,因为很多地方都会涉及版本不一致问题,需要安装更新版本的gcc、cmake、我用的是较低版本
较低的版本也容易适配
我安装的是0.10.7
cmake \
-D CMAKE_BUILD_TYPE=release\
-D BUILD_STATIC_LIBS=ON \
-D BUILD_SHARED_LIBS=OFF \
-D CMAKE_INSTALL_PREFIX=/usr/local/jsoncpp \
-D CMAKE_C_COMPILER=/usr/bin/gcc \
-D CMAKE_CXX_COMPILER=/usr/bin/g++ \
-D CMAKE_CXX_FLAGS="-fPIC" \
-D CMAKE_C_FLAGS="-fPIC" \
-G "Unix Makefiles" ../..
之前下了最新的,但是有一些问题,报错
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /home/drcomtudong/jsoncpp/lib/libjsoncpp.a(json_reader.cpp.o): relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /home/drcomtudong/jsoncpp/lib/libjsoncpp.a(json_value.cpp.o): relocation R_X86_64_32 against `.bss' can not be used when making a shared object; recompile with -fPIC
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /home/drcomtudong/jsoncpp/lib/libjsoncpp.a(json_writer.cpp.o): relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: final link failed: Nonrepresentable section on output
collect2: error: ld returned 1 exit status
make: *** [HttpAuth.so] Error 1
先麦格雷,到后面有时间再来分析一下。
//json ->c++ string/int
#include <iostream>
#include <json/json.h> // 包含JsonCpp头文件
int main() {
std::string jsonText = "{\"name\": \"John\", \"age\": 30}";
Json::Value root;
Json::Reader reader;
if (reader.parse(jsonText, root)) {
// 成功解析JSON数据
std::string name = root["name"].asString();
int age = root["age"].asInt();
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
} else {
// 解析失败
std::cout << "Failed to parse JSON" << std::endl;
}
return 0;
}
//c++ ->json
#include <iostream>
#include <json/json.h>
struct Person {
std::string name;
int age;
};
int main() {
// 创建一个C++结构实例
Person person;
person.name = "John";
person.age = 30;
// 创建一个Json::Value对象,用于存储转换后的JSON数据
Json::Value jsonPerson;
// 将C++数据转换为JSON数据
jsonPerson["name"] = person.name;
jsonPerson["age"] = person.age;
// 使用Json::StreamWriterBuilder将JSON数据序列化为字符串
Json::StreamWriterBuilder writer;
std::string jsonString = Json::writeString(writer, jsonPerson);
// 打印生成的JSON字符串
std::cout << "JSON String: " << jsonString << std::endl;
return 0;
}
总结一下,没想到cmake还能这么用,纯纯骚操作!