Skip to content
cpp
#ifndef JSONTEST_H
#define JSONTEST_H

#include <iostream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

class TempHumi
{
public:
    TempHumi(int id, float temp, float humi)
        : id(id), temp(temp), humi(humi) {};
    int id;
    float temp;
    float humi;
};

void toJson1()
{
    // 创建JSON 对象
    json j;
    j["id"] = 123;
    j["name"] = "test";
    j["age"] = 20;
    j["address"]["city"] = "Beijing";
    j["address"]["street"] = "Chaoyang Road";

    // 转为字符串并输出
    std::cout << j.dump(4) << std::endl;
}

void toJso2()
{
    // 创建JSON 对象
    json j;
    j["id"] = 1234;
    j["name"] = "test";
    j["age"] = 20;

    json add;
    add["city"] = "Beijing";
    add["street"] = "Chaoyang Road";

    j["address"] = add;

    // 转为字符串并输出
    std::cout << j.dump(4) << std::endl;
}

void toJson3()
{
    // 使用初始化列表创建JSON 对象
    json j =
        {
            {"id", 1234},
            {"name", "test"},
            {"age", 20},
            {"address",
             {{"city", "Beijing"},
              {"street", "Chaoyang Road"}}}};

    // 转为字符串并输出
    std::cout << j.dump(4) << std::endl;
}

void jsonToObj(const json &j, TempHumi &th)
{
    th.id = j["id"].get<int>();
    th.temp = j["temp"].get<float>();
    th.humi = j["humi"].get<float>();

    std::cout << "ID: " << th.id << ", Temp: " << th.temp << ", Humi: " << th.humi << std::endl;
}

void stringTOJson(const std::string &str)
{
    // 将字符串转换为JSON对象
    json j = json::parse(str);

    // 转为字符串并输出
    std::cout << j.dump(4) << std::endl;
}
#endif // JSONTEST_H