samedi 28 octobre 2017

Decouple POJO from rapidjson

If there is a POJO class, for example

class Person {
public:
    Person (string name, int age) ...
private:
    string name;
    int age;
};

To use RapidJson, I can get the following working (somewhat pseudo code).

To deserialize 

    Document document;   
   ...

    Value k("name", allocator);
    Value v("john", allocator);

    document.AddMember(namespaceKey, namespaceValue, allocator);  


To serialize

StringBuffer strbuf;
Writer<StringBuffer> writer(strbuf);
document.Accept(writer);
return strbuf.GetString();

So just add a few methods seems working fine.

class Person {
public:
    Person (string name, int age) ...
    void deserialize();
    string serialize();
private:
    string name;
    int age;
    Document document;
};

However, POJO class has strong coupling with RapidJson. It there anyway to totally decouple the two?

One idea is have (somewhat pseudo code)

class SomeMapper {
public:
    Document& deserialize(SomeInterface& someInteface) ;
    string serialize(Document& document);
private:
    Document document;
};

For serialize() above code should work. But to deserialize, define

class SomeInterface {
public:
    virtual Document& deserialize(Document& document) = 0;
};

and have POJO class inherit SomeInterface and implement deserialize(). The problem is in deserialize() method of POJO class, there will still be RapidJson code.

Did anyone encounter this before and came up with a cleaner solution to decouple POJO such that POJO can completely be RapidJason independent?

Having a base class to wrap up Rapidjson code might work but looking for ideas to totally decouple POJO and RapidJson.

Aucun commentaire:

Enregistrer un commentaire