user1899020
user1899020

Reputation: 13575

How to use json c++ with my own object?

I am planning to use json c++ at https://github.com/nlohmann/json#examples . After reading its simple examples, I still have no idea how to use it with my own object? For example, I have a class

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

private:
    int m_id;
    string m_name;
};

How to use json to read and write (deserialize and serialize) a Student object?

Upvotes: 3

Views: 9076

Answers (2)

this is another way to do the conversion from json to custom class, that actually fits the best practices defined in the official repo from nlohmann here

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

cpp:

#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;
}

example:

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);

Upvotes: 9

bl4ckb0ne
bl4ckb0ne

Reputation: 1217

This library doesnt seems to have any interaction with a class for serialization and deserialization. But you can implement it yourself with a constructor and a 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;
};

Upvotes: 5

Related Questions