Let's say I have a REST service which returns a JSON object with the following scheme:
{
"id" : 1
"name" : "Peter"
"age" : 25
}
I have an application written in C++ which receives this object and deserializes for later use. I need a data structure to store the object.
I can implement that using either a struct:
struct person
{
int id;
string name;
int age;
};
and having a helper function to initialize the struct:
// Returns a person deserialized from a JSON object
person fromJson(JsonObject obj);
// Usage:
auto personInfo = fromJson(/* JSON object from REST service */);
Or having a class with getters, setters and a constructor which takes a JsonObject as a parameter and does the deserialization by itself:
class person
{
public:
// Deserialized a JSON object and initializes the private fields
person(JsonObject obj);
int id() const;
string name() const;
int age() const;
void setId(int id);
void setName(string name);
void setAge(int age);
private:
int _id;
int _name;
int _age;
};
// Usage:
person personInfo{ /* JSON object from REST service */ };
Given that the data will be stored on a client machine, displayed, possibly edited then sent back to the REST service, which implementation would be more suitable to use? Since I would use the data structure only to store data(using the setters/getters shouldn't trigger anything else than setting/getting the value) I can't really think of any benefits of one over another other than personal preference.
I would go the class route. In that case the object you're working with can do everything that needs doing (no helper methods to create the object) and it's clear and obvious what's being worked with. What's more, as your application becomes more complicated it'll make it easier to keep the structure and functionality of your objects logical and useful.
In C++, the only difference between a struct
and a class
is the default access specifier which is public
for structs
and private
for classes. You can have a struct
with member functions, constructors, move assignment, etc., and it's identical to a class
. Doing the de-serialization in the constructor or having a free function is entirely up to you. Another option would be to have a static
member function in person
that returns a person
object.
class person {
public:
static person fromJSON(JsonObject const& src) { ... }
};
auto p = person::fromJSON(source);
In any case, you will need a lot of validation code because you are passing in what could effectively be an arbitrary JSON object, and be sure to follow the rule of 3/5/0 so you don't accidentally inhibit move semantics.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.