3

I'm a student, and developing a PC-Client with cpp. I do not know how to deal with which rapidjson with encoding Unicode. I always get a messy code. I am a jackeroo about cpp, how can i get the correct result? I will appreciate it much!

Just show a example:

class Test {
    // I have got the string of json
    // eg: { "name" : "小明" }
    public : void test(const std::string& data) {
        rapidjson::Document json;
        json.Parse<0>(data.c_str());

        // there are a method GetString() , return a string
        // The name value are another Chinese characters(I guess which because of its encoding).
        // I want to get a wstring which value is "小明"(Not a messy code). How can i do ? 
        std::string name = json["name"].GetString();
    }
};


// I had used this method
// But still got a messy code
str::UnicodeToAnsi();
毕晓峰
  • 131
  • 1
  • 8
  • Show what you have tried so far (code). – Blacktempel Feb 26 '16 at 03:50
  • Post some codes that you have tried before.. – Shree Krishna Feb 26 '16 at 04:03
  • convert `std::string` to `std::wstring`. It's not specific to json libraries – Barmak Shemirani Feb 26 '16 at 05:22
  • @BarmakShemirani It's not this problem which convert string to wstring. It`s that get a wstring from the json. – 毕晓峰 Feb 26 '16 at 05:49
  • Maybe you could check what `UTF-8` is and how it is represented, then probably you don't need to consider `wstring` at all. – Mine Feb 26 '16 at 06:16
  • @Mine I thought the problem would be the encoding before. I look for API of rapidjson, we get the return json's encoding type is Unicode, and I use str::UnicodeToAnsi() method, get a error result. I am confused. Until i try to use the method below, i get a correct wstring. But i am thinking of whether a method can convert the string from rapidjson to a correct encoding string? – 毕晓峰 Feb 27 '16 at 15:49
  • @毕晓峰 please be noted that `Unicode` is different from `encoding`. `Unicode` can be encoded to `UTF-8`, `UTF-16` or others. – Mine Feb 29 '16 at 01:39

1 Answers1

7
#include <codecvt>
#include <string>

// convert UTF-8 string to wstring
std::wstring utf8_to_wstring (const std::string& str)
{
    std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv;
    return myconv.from_bytes(str);
}

// convert wstring to UTF-8 string
std::string wstring_to_utf8 (const std::wstring& str)
{
    std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv;
    return myconv.to_bytes(str);
}

Convert wstring to string encoded in UTF-8 Thanks!

Community
  • 1
  • 1
毕晓峰
  • 131
  • 1
  • 8