Skip to content

How to serialize/deserialize custom scalar type? #3435

Answered by krishna116
krishna116 asked this question in Q&A
Discussion options

You must be logged in to vote

After some test, finally I got the working solution, It may be an example for other people.

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

// A custom scalar type.
class email_t
{
    std::string email_;
public:
    email_t()=default;
    email_t(const std::string &str){ email_ = str; }
    email_t(const char* str){ email_ = str; }
    email_t &operator=(const std::string &str){ email_ = str; return *this; }
    email_t &operator=(const char* str){ email_ = str; return *this; }
    std::string str() const{ return email_; }
    bool empty() const{ return email_.empty(); }
};

// Add custom scalar type support for serializing and deserializing.
namespace nlohmann {
    template <>
    st…

Replies: 4 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@gregmarr
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by nlohmann
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants