I want to parse a json file, where some elements are common each time while others are different based on a type. For example a message json:
{
"title": string,
"body": string,
"type": int (0 for email, 1 for sms, 2 for terminal)
"typeProperties": {
// Different based on type value
}
}
I ended up to the following code to represent the json object:
#include <string>
#include <vector>
#include <iostream>
class Message {
public:
int id;
std::string title;
std::string body;
int type; // 0 - Email, 1 - SMS, 2 - Terminal
};
class Email : public Message {
public:
std::string emailRecipients;
std::string emailCC;
};
class Sms : public Message {
public:
std::string phoneNumber;
};
class Terminal : public Message {
public:
int terminalId;
};
std::vector<Message*> list_msg;
int main(int argc, char** argv) {
Email mail;
mail.id = 1;
mail.title = "title1";
mail.body = "body1";
mail.type = 0;
mail.emailRecipients = "text1";
mail.emailCC = "text2";
list_msg.push_back(&mail);
Terminal tms;
tms.id = 2;
tms.title = "title2";
tms.body = "body2";
tms.type = 1;
tms.terminalId = 123;
list_msg.push_back(&tms);
for (auto m : list_msg) {
std::cout << "id: " << m->id << ", type: " << m->type << std::endl;
if (m->type == 0) {
Email *tmp = static_cast<Email*>(m);
std::cout << ">>>> recipient: " << tmp->emailRecipients << ", cc: " << tmp->emailCC << std::endl;
} else if (m->type == 1) {
Terminal *tmp = static_cast<Terminal*>(m);
std::cout << ">>>> terminalId: " << tmp->terminalId << std::endl;
}
}
}
Questions:
- Is the above code correct?
- From performance perspective, can this be optimized?
- If I don't use inheritance and have one class Message with a boost::variant member - what are the pros and cons of this approach?