2013-02-02 84 views
1

如何使用rapidjson將對象序列化爲std :: string? 我已經實現如何使用rapidjson序列化對象到std :: string(實現序列化)?

class Person{ 
public: 
    std::string name; 
    uint64 id; // uint64 is typedef 

    template <typename Writer> 
    void Serialize(Writer& writer) const { 
     writer.StartObject(); 
     writer.String("name"); 
     writer.String(name); 
     writer.String(("id")); 
     writer.Uint64(id); 
     writer.EndObject(); 
    } 
    std::string serialize(){ 
     FileStream s(stdout); 
     PrettyWriter<FileStream> writer(s); 
     Serialize(writer); 
     return ? /// There is a problem 

    } 
} 

問題在連載的功能是什麼回來?

回答

2

沒有。你已經發送到stdout

如果您不想將輸出流式傳輸到文件,請不要使用FileStream;使用PrettyWriter的一些其他模板參數,它存儲並允許您提取字符串。

通過快速瀏覽文檔,StringBuffer看起來很有前途。這是GenericStringBuffer<UTF8<> >的類型別名。

0

試試這個:

std::string serialize() { 
    GenericStringBuffer<UTF8<> > buffer; 
    Writer<GenericStringBuffer<UTF8<> > > writer(buffer); 

    Serialize(writer); 

    return buffer.GetString(); 
} 
2

問題是很老,如果你還在尋找答案,那麼這裏就是由@Lightness種族在軌道

class Person{ 
public: 
    std::string name; 
    uint64 id; // uint64 is typedef 

    template <typename Writer> 
    void Serialize(Writer& writer) const { 
     writer.StartObject(); 
     writer.String("name"); 
     writer.String(name); 
     writer.String(("id")); 
     writer.Uint64(id); 
     writer.EndObject(); 
    } 
    std::string serialize(){ 
     StringBuffer s; 
     Writer<StringBuffer> writer(s); 
     Serialize(writer); 
     return s.GetString(); 
    } 
} 

建議的一個你也可以在這裏查看示例代碼:simplewriter.cpp