我打算在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;
};
如何使用json读取和写入(反序列化和序列化)Student
对象?
答案 0 :(得分:5)
这个库似乎与serialization and deserialization的类没有任何交互。 但是你可以用构造函数和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;
};
答案 1 :(得分:1)
这是将json转换为自定义类的另一种方法,实际上符合此处nlohmann官方回购中定义的最佳实践
https://github.com/nlohmann/json#arbitrary-types-conversions
h:
$ echo '
set rc [catch {exec sh -c {echo to stdout; echo to stderr >&2} 2>@stderr} result]
puts "rc=$rc result=>$result<"
' | tclsh 2>/dev/null
rc=0 result=>to stdout<
cpp:
#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
示例:
#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;
}