如何使用json c ++和我自己的对象?

use*_*020 2 c++ serialization json deserialization

我打算在https://github.com/nlohmann/json#examples上使用json c ++ .阅读完简单的例子之后,我仍然不知道如何将它与我自己的对象一起使用?例如,我有一个班级

class Student
{
public:
    Student(int id, string const& name)
       : m_id(id), m_name(name)
    {}   

private:
    int m_id;
    string m_name;
};
Run Code Online (Sandbox Code Playgroud)

如何使用json读取和写入(反序列化和序列化)Student对象?

ΦXo*_*a ツ 7

这是将 json 转换为自定义类的另一种方法,它实际上符合 nlohmann 此处的官方 repo 中定义的最佳实践

https://github.com/nlohmann/json#arbitrary-types-conversions

H:

#ifndef STUDENT_H
#define STUDENT_H

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

class Student
{
public:
    Student();
    Student(int id, const std::string &name);
    int getId() const;
    void setId(int newId);

    std::string getName() const;
    void setName(const std::string &newName);

private:
    int m_id;
    std::string m_name;
};

//json serialization
inline void to_json(nlohmann::json &j, const Student &s)
{
    j["id"] = s.getId();
    j["name"] = s.getName();
}

inline void from_json(const nlohmann::json &j, Student &s)
{
    s.setId((j.at("id").get<int>()));
    s.setName(j.at("name").get<std::string>());
}
#endif // STUDENT_H
Run Code Online (Sandbox Code Playgroud)

cp:

#include "Student.h"

#include<string>

Student::Student() : Student(0, "")
{

}

Student::Student(int id, const std::string &name) : m_id{id}, m_name{name}
{

}

int Student::getId() const
{
    return this->m_id;
}

void Student::setId(int newId)
{
    m_id = newId;
}

std::string Student::getName() const
{
    return this->m_name;
}

void Student::setName(const std::string &newName)
{
   this->m_name = newName;
}
Run Code Online (Sandbox Code Playgroud)

例子:

Student s{0, "x"};
nlohmann::json studentJson = s;
std::cout << "Student from object: " << s.getId() << std::endl;
std::cout << "Student from json: " << studentJson.at("id").get<int>() << std::endl;

//String
std::string jSt = studentJson.dump();  //{"id":0,"name":"x"}
Student s2 = studentJson;
Student s3 = nlohmann::json::parse(jSt);
Run Code Online (Sandbox Code Playgroud)


bl4*_*0ne 5

这个库似乎没有与类进行任何交互以进行序列化和反序列化.但是你可以使用构造函数和getter自己实现它.

using json = nlohmann::json;

class Student
{
public:
    Student(int id, string const& name)
       : m_id(id), m_name(name)
    {} 
    Student(json data)
       : m_id(data["id"]), m_name(data["name"])
    {}

    json getJson()
    {
        json student;
        student["id"] = m_id;
        student["name"] = m_name;

        return student;
    }

private:
    int m_id;
    string m_name;
};
Run Code Online (Sandbox Code Playgroud)