备注:本文展示一个使用nlohmann的简单示例,仅供参考,这是示例代码,非常简略,只是为了初学者方便学习使用。
本示例使用CLion创建工程,直接在工程代码中引入nlohmann,将其放在本工程的中
1, 目录结构
下载地址:
https://github.com/nlohmann/json/tree/develop/single_include/nlohmann/json.hpp
2,CMakeLists.txt文件
cmake_minimum_required(VERSION 3.21)
project(nlohmanndemo)
set(CMAKE_CXX_STANDARD 14)
include_directories( CMAKE_CURRENT_SOURCE_DIR/nlohmann)
add_executable(nlohmanndemo main.cpp)
3,main.cpp文件
#include <iostream>
#include "nlohmann/json.hpp"
using nlohmann::json;
struct VersionData
{
int64_t id;
int32_t version;
std::string url;
std::string name;
// 输出运算符重载
friend std::ostream &operator<<( std::ostream &output, const VersionData &obj)
{
output << "id:" << obj.id << "Version:" << obj.version ;
return output;
}
};
int main() {
std::string response_body = "[\n"
" {\n"
" \"name\": \"project1\",\n"
" \"extra_data\": {\n"
" \"desc\": \"comment1\"\n"
" },\n"
" \"url\": \"https://a.b.c.0.zip\",\n"
" \"id\": 100000,\n"
" \"version\": 4\n"
" }\n,"
" {\n"
" \"name\": \"projectB\",\n"
" \"extra_data\": {\n"
" \"desc\": \"comment2\",\n"
" \"author\": \"zhangsan\"\n"
" },\n"
" \"url\": \"https://a.b.c/1.zip\",\n"
" \"id\": 200000,\n"
" \"version\": 5\n"
" }"
"]";
nlohmann::json response_json = nlohmann::json::parse(response_body, nullptr, false);
std::vector<VersionData> versionDataList;
if(response_json.is_array()) {
std::cout << "array!" << std::endl;
for (auto p : response_json) {
VersionData versionData;
versionData.version = p["version"];
versionData.id = p["id"];
versionData.name = p["name"];
versionData.url = p["url"];
versionDataList.push_back(versionData);
std::cout << "id:" << versionData.id << std::endl;
}
std::cout << "versionDataList:" << std::endl;
for (std::vector<VersionData>::iterator iter = versionDataList.begin(); iter != versionDataList.end(); iter++) {
std::cout << (*iter).id << std::endl;
std::cout << (*iter) << std::endl;
}
} else {
std::cout << "not array" << std::endl;
}
std::cout << "done of end!" << std::endl;
return 0;
}
4, 执行结果
cmake .
make
./nlohmanndemo
xxx-MacBook-Pro nlohmanndemo % cmake .
-- Configuring done
-- Generating done
-- Build files have been written to: xxx/CLionProjects/nlohmanndemo
xxx-MacBook-Pro nlohmanndemo % make
Consolidate compiler generated dependencies of target nlohmanndemo
[ 50%] Building CXX object CMakeFiles/nlohmanndemo.dir/main.cpp.o
[100%] Linking CXX executable nlohmanndemo
[100%] Built target nlohmanndemo
xxx-MacBook-Pro nlohmanndemo % ./nlohmanndemo
array!
id:100000
id:200000
versionDataList:
100000
id:100000Version:4
200000
id:200000Version:5
done of end!