3

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?

user1899020
  • 13,167
  • 21
  • 79
  • 154
  • 1
    AFAIK nlohmann-json is not a serialization library. It converts json string into c++ containers and vice-versa. You may want to checkout ThorsSerializer https://github.com/Loki-Astari/ThorsSerializer – Arunmu Jul 12 '16 at 18:09
  • @Arunmu That is very good. Does ThorsSerializer support class polymorphism (base class pointer pointing to a derived class)? – user1899020 Jul 12 '16 at 18:19
  • Sorry, no idea, I haven't used it myself yet. – Arunmu Jul 12 '16 at 18:26
  • Unfortunately, most of the C++ JSON libraries do not support serialization and deserialization to/from classes. – adam Jul 12 '16 at 19:17
  • See response http://stackoverflow.com/a/39904141/606515 for JSON to/from C++ object conversion lib. – kola Oct 07 '16 at 21:12
  • @user1899020 from the author of ThorsSerializer. Yes it does. – Martin York Jul 08 '19 at 01:25
  • @Arunmu Why do you say nlohmann/json is not a serialization library. Because "serialization" always refers to a binary format and JSON is text? Thanks! – Patrick Jan 11 '21 at 19:42
  • I would guess because it cannot just take an object and serialize it, you have to write all the plumbing yourself even if you can wrap it up in to_json and from_json methods. In most languages you can just give a serializer and object and it will use some default rules to make the json. – Mant101 Jan 14 '21 at 12:25

2 Answers2

9

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);
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
5

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;
};
bl4ckb0ne
  • 1,097
  • 2
  • 15
  • 30