C++ 使用nlohmann/json.hpp库读写json字符串

1. json库

我个人比较喜欢 nlohmann/json.hpp 这个库,因为它只需要一个hpp文件即可,足够轻量!

这是它的github地址

2. 简单实例代码

#include <iostream>
#include <json.hpp>
#include <fstream>
#include <string>

using namespace nlohmann;
using namespace std;

string GenerateJsonStr()
{
    /*
    * 生成json格式字符串
    *
    * 预计的json格式文本为:
    * {
    *   "name": "ashui",
    *   "school": ["A school", "B school", "C school"],
    *   "money": [124.5, 345.3, 457.4],
    *
    *   physic
    *   {
    *       "height": 180,
    *       "weight": 68.5
    *   }
    * }
    */

    json json_data;
    json_data["name"] = "ashui";
    json_data["school"] = { "A school", "B school", "C school" };
    json_data["money"] = { 124.5, 345.3, 457.4 };

    json physic_data;
    physic_data["height"] = 180;
    physic_data["weight"] = 68.5;
    json_data["physic"] = physic_data;

    return json_data.dump();
}

bool SaveJsonStr()
{
    string jsonStr = GenerateJsonStr();

    // Save to file
    std::ofstream file("output.json");

    if (file.is_open())
    {
        file << jsonStr;

        file.close();

        std::cout << "dump string:" << std::endl;
        std::cout << jsonStr << std::endl;

        return true;
    }
    
    return false;
}

bool ReadJsonObj()
{
    std:ifstream jsonFile("D:\\Project\\C++\\json_example\\x64\\Debug\\output.json");

    if (!jsonFile.is_open())
    {
        std::cout << "Open json file error" << std::endl;
        return false;
    }

    json jsonData;
    try
    {
        jsonData = json::parse(jsonFile);

        if (jsonData.is_null())
        {
            std::cout << "The json object is null" << std::endl;
            return false;
        }

        std::string name = jsonData["name"];
        std::vector<std::string> school = jsonData["school"];
        std::vector<float> money = jsonData["money"];

        int height = jsonData["physic"]["height"];
        float weigjt = jsonData["physic"]["weight"];

        std::cout << std::endl;
        std::cout << "parse string:" << std::endl;
        std::cout << "name: " << name << std::endl;
        std::cout << "height: " << height << std::endl;
        std::cout << "weigjt: " << weigjt << std::endl;

        std::cout << "school: ";
        for (auto s : school)
        {
            std::cout << s << ", ";
        }
        std::cout << std::endl;

        std::cout << "money: ";
        for (auto m : money)
        {
            std::cout << m << ", ";;
        }
        std::cout << std::endl;
    }
    catch (const std::exception& e)
    {
        std::cout << "json error: "<< e.what() << std::endl;
        return false;
    }

    return true;
}

int main()
{
    SaveJsonStr();
    ReadJsonObj();
}

值得注意的是,在使用[]读取json内容时,最外层一定要套一个try-catch用以补获异常,这样比起一个一个元素去判断是否为空、是否为数组等要方便且安全!

使用C++创建TCP通讯可以使用socket,而传输和接收json数据可以使用nlohmann/json。下面是基本的代码示例: 发送端: ```cpp #include <iostream> #include <string> #include <nlohmann/json.hpp> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> using json = nlohmann::json; int main() { // 创建socket int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sock == -1) { std::cerr << "socket creation failed" << std::endl; return 1; } // 设置服务器地址和端口号 struct sockaddr_in server_addr; server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); server_addr.sin_port = htons(12345); // 连接服务器 if (connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) { std::cerr << "connection failed" << std::endl; return 1; } // 构造json数据 json j; j["name"] = "Alice"; j["age"] = 20; std::string json_str = j.dump(); // 发送数据 if (send(sock, json_str.c_str(), json_str.size(), 0) == -1) { std::cerr << "send failed" << std::endl; return 1; } // 关闭socket close(sock); return 0; } ``` 接收端: ```cpp #include <iostream> #include <string> #include <nlohmann/json.hpp> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> using json = nlohmann::json; int main() { // 创建socket int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sock == -1) { std::cerr << "socket creation failed" << std::endl; return 1; } // 设置本机地址和端口号 struct sockaddr_in my_addr; my_addr.sin_family = AF_INET; my_addr.sin_addr.s_addr = INADDR_ANY; my_addr.sin_port = htons(12345); // 绑定socket if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr)) == -1) { std::cerr << "bind failed" << std::endl; return 1; } // 监听socket if (listen(sock, SOMAXCONN) == -1) { std::cerr << "listen failed" << std::endl; return 1; } // 接收连接 struct sockaddr_in client_addr; socklen_t client_addr_len = sizeof(client_addr); int client_sock = accept(sock, (struct sockaddr*)&client_addr, &client_addr_len); if (client_sock == -1) { std::cerr << "accept failed" << std::endl; return 1; } // 接收数据 char buffer[1024]; int length = recv(client_sock, buffer, sizeof(buffer), 0); if (length == -1) { std::cerr << "receive failed" << std::endl; return 1; } // 解析json数据 std::string json_str(buffer, length); json j = json::parse(json_str); // 输出数据 std::cout << "name: " << j["name"].get<std::string>() << std::endl; std::cout << "age: " << j["age"].get<int>() << std::endl; // 关闭socket close(client_sock); close(sock); return 0; } ``` 上面的代码示例中,发送端使用nlohmann/json构造json数据,并使用socket发送数据;接收端使用socket接收数据,并使用nlohmann/json解析json数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值