Sword nlohmann::json的使用

#include <iostream>
#include <string>
#include<sstream>
#include "json.hpp"

// C++ 之 nlohmann::json 的使用

/*
知识补充:
    1. nlohmann::json编译依赖于-std=c++11
*/

// 初始化
void test1()
{
    nlohmann::json obj1, obj2, obj3, obj4;
    const char* p = "{\"age\":22,\"gender\":true,\"name\":\"jack\",\"pet\":{\"name\":\"wang\",\"type\":\"dog\"}}";
    std::istringstream ostr("{\"age\":45,\"gender\":true,\"name\":\"skipper\",\"pet\":{\"name\":\"wang\",\"type\":\"dog\"}}");
    
    // 示例json
    // {"age":22,"family":[{"call":"father","name":"adam"},{"call":"mother","name":"eve"},
{"call":"wife","name":"shine"}],"gender":true,"name":"jack","pet":{"name":"wang","type":"dog"}}
// a.赋值构造 obj1["name"] = "jack"; //字符串 obj1["age"] = 22; //整数 obj1["gender"] = true; //布尔值 obj1["pet"] = { {"type","dog"}, {"name" , "wang" } }; //对象 /* 知识补充: nlohmann::json 中的数组是用{},而不是[] */ obj1["family"] = { {{"call","father"}, {"name" , "adam" }},{{"call","mother"}, {"name" , "eve" }} }; //数组 obj1["family"][2] = { {"call","wife"}, {"name" , "shine" } }; // 元素赋值 // b.直接构造 obj2 = { {"type","dog"}, {"name" , "wang" } }; // c.字符串构造 /* 知识补充: 注意nlohmann::json::parse()函数签名 nlohmann::json::parse(const char*, const char*) */ obj3 = nlohmann::json::parse(p, p + strlen(p)); // d.字符流构造(也可以使用std::ifstream之类替换) ostr >> obj4; } // 属性提取 void test2() { nlohmann::json tmp; const char* p = "{\"age\":22,\"gender\":true,\"name\":\"jack\",\"pet\":{\"name\":\"wang\",\"type\":\"dog\"}}"; nlohmann::json obj = nlohmann::json::parse(p, p + strlen(p)); // nlohmann::json为空判断(不可以使用NULL) if (nullptr == tmp) { std::cout << "empty" << std::endl; } // 提取字符串 std::string name = obj["name"].get<std::string>(); // 提取整型 int age = obj["age"].get<int>(); // 提取布尔值 bool gender = obj["gender"].get<bool>(); // 提取对象 nlohmann::json pet = obj["pet"]; std::cout << name << ":" << age << ":" << gender << std::endl; } // 数组遍历 void test3() { const char* p = "[{\"name\":\"1\",\"type\":\"a\"},{\"name\":\"2\",\"type\":\"b\"},
{\"name\":\"c\",\"type\":\"a\"},{\"name\":\"4\",\"type\":\"d\"}]
"; nlohmann::json obj; obj = nlohmann::json::parse(p, p + strlen(p)); if (obj.empty()) { // 数组为空 std::cout << "The array is empty" << std::endl; return; } // 遍历数组 for (auto& item : obj.items()) { // item.value() = {"name":"1","type":"a"} std::cout << item.value() << std::endl; } } int main() { //test1(); //test2(); test3(); return 0; }

https://github.com/nlohmann/json

posted on 2022-06-27 21:17  寒魔影  阅读(1761)  评论(0编辑  收藏  举报

导航