mardi 11 juillet 2017

Represent json file with a set of different data members to a C++ class

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

Shall I use inheritance to represent the json to C++ ? Shall I use a factory method to instantiate each time the appropriate class? Is there any other recommended approach for this?

class Message {
   std::string title;
   std::string body;
   int type; // 0 - Email, 1 - SMS, 2 - Terminal
}

class Email : public Message {
  std::vector<std::string> emailRecipients;
  std::vector<std::string> emailCC;
}
class Sms : public Message {
  std::string  phoneNumber; 
}
class Terminal : public Message {
  int terminalId;
}

Can I use a container of base class objects and somehow access the specific data members based on the type?

std::vector<Message> messages;

Aucun commentaire:

Enregistrer un commentaire