繁体   English   中英

将 json++ 实现转换为使用 rapidJSON:处理字符串和 wstring 的混合

[英]converting json++ implementation to use rapidJSON: handling mixture of string and wstring

我正在将一些最初使用 json++ 库的代码转换为现在使用 rapidJSON。 该代码使用 json 文件对各种对象进行序列化和反序列化。 在 json++ 中,它看起来像这样:

连载:

string normal = "normal";
wstring wide = L"wide";
JSON::Object json;
    
json["normal"] = normal;
json["wide"] = wide;

反序列化:

string normalCopy = json["normal"].as_string();
wstring wideCopy = json["wide"].as_wstring();

我还没有找到一种使用 rapidJSON 序列化和反序列化混合字符串的简单方法。

这里有两个例子:

    #include <rapidjson/document.h>
    #include <rapidjson/writer.h>
    #include <iostream>
    #include <sstream>
    
    using namespace std;
    using namespace rapidjson;
    
    int main()
    {
        string normalstr = "This is a normal string";
        wstring widestr = L"This is a wide string";
    
        Document doc;
        auto& alloc = doc.GetAllocator();
    
        Value val(kObjectType);
    
        val.AddMember("normal", normalstr, alloc);
        val.AddMember("wide", widestr, alloc); // <-- cannot convert
    
        StringBuffer buffer;
        Writer<StringBuffer> writer(buffer);
        val.Accept(writer);
    
        ostringstream jsonOutput;
    
        jsonOutput << buffer.GetString();
    
        cout << jsonOutput.str() << endl;
    }

    #include <rapidjson/document.h>
    #include <rapidjson/writer.h>
    #include <iostream>
    #include <sstream>
    
    using namespace std;
    using namespace rapidjson;
    
    int main()
    {
        string normalstr = "This is a normal string";
        wstring widestr = L"This is a wide string";
    
        Document doc;
        auto& alloc = doc.GetAllocator();
    
        GenericValue<UTF16<> > val(kObjectType);
    
        val.AddMember(L"normal", normalstr, alloc); // <-- cannot convert
        val.AddMember(L"wide", widestr, alloc);
    
        GenericStringBuffer<UTF16<> > buffer;
        Writer<GenericStringBuffer<UTF16<> >, UTF16<>> writer(buffer);
        val.Accept(writer);
    
        ostringstream jsonOutput;
    
        jsonOutput << buffer.GetString();
    
        cout << jsonOutput.str() << endl;
    }

根据我的理解,RapidJSON 设置为在处理对象级粒度时专门与 std::string (UTF-8) 或 std::wstring (UTF-16) 一起使用。

当我想要序列化的 object 中有两种类型时,我是否需要从 wstring 转换为字符串,或者 API 中是否有我不知道的可用内容?

我认为您需要在这里使用转换,我通过 RapidJSON 的 doc 和 src 有 go ,并确认我们不能将GenericValueValue混合。

我们可以使用wstring_convert ,将此答案作为参考。

或与boost

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM