C++ rapidjson Unicode编码总结

来源:互联网 发布:网络热词2015 编辑:程序博客网 时间:2024/06/06 15:42

rapidjson默认为UTF-8编码,其中提供了Unicode、ASCII等其他编码。

  • rapidjson::Document
    rapidjson::Document的原型为:typedef GenericDocument<UTF8<> > Document;

  • rapidjson::Value
    rapidjson::Value的原型为:typedef GenericValue<UTF8<> > Value;
    使用Unicode编码时,需 自己定义为:typedef rapidjson::GenericValue<rapidjson::UTF16<> > ValueUTF16;

  • rapidjson::StringBuffer
    rapidjson::StringBuffer的原型为:typedef GenericStringBuffer<UTF8<> > StringBuffer;
    使用Unicode编码时,需自己定义为:typedef rapidjson::GenericStringBuffer<rapidjson::UTF16<> > StringBufferUTF16;

  • rapidjson::Writer
    rapidjson::Writer为模板类,其模板原型为:template<typename OutputStream, typename SourceEncoding = UTF8<>, typename TargetEncoding = UTF8<>, typename StackAllocator = CrtAllocator>
    class Writer

    其中有四个类型,只需关注前三个。第一个OutputStream为输出流,一般为rapidjson::StringBuffer;
    第二个SourceEncoding为原编码,也就是生成JSon字符串时使用的编码格式;
    第三个TargetEncoding为输出编码,也就是你想要得到的字符串是哪种编码;
    举个例子:如果原编码和输出编码都为UTF-8,则只需要默认的即可;如果原编码和输出编码都为UTF-16,则需要重新定义为typedef rapidjson::Writer<StringBufferUTF16, rapidjson::UTF16<>, rapidjson::UTF16<> > WriterUTF16;同理,其他编码转化义可。

下面写个简单的例子(使用Unicode生成JSon字符串):

typedef rapidjson::GenericDocument<rapidjson::UTF16<> > DocumentUTF16;typedef rapidjson::GenericValue<rapidjson::UTF16<> >    ValueUTF16;typedef rapidjson::GenericStringBuffer<rapidjson::UTF16<> > StringBufferUTF16;typedef rapidjson::Writer<StringBufferUTF16, rapidjson::UTF16<>, rapidjson::UTF16<> >   WriterUTF16;    DocumentUTF16   JSonDoc;    DocumentUTF16::AllocatorType & alloca = JSonDoc.GetAllocator();    ValueUTF16 Obj(rapidjson::kObjectType);    ValueUTF16 NameObj(rapidjson::kStringType);    std::wstring strName = _T("Microsoft[微软]");    NameObj.SetString(strName.c_str(), strName.size(), alloca);    Obj.AddMember(_T("Name"), NameObj, alloca);    Obj.AddMember(_T("Age"), 26, alloca);    Obj.AddMember(_T("Sex"), true, alloca);    StringBufferUTF16 buf;    WriterUTF16 writer(buf);    Obj.Accept(writer);    std::wstring strBuf = buf.GetString();
0 0
原创粉丝点击