简体   繁体   中英

How to convert a JSON file to UTF-8 format in c/c++?

I was able to generate a JSON file using c++ & verified with JSON lint .The file I am generating has correct format [No matters whatever is there is file]. As I am new to Encoding/Decoding so do not have much idea related to this at this instance .Is there any way I can convert this JSON file to UTF-8 format in c or c++ .

Is there any way I can convert this JSON file to UTF-8 format in c or c++ .

you are not saying from what encoding you want to convert, if you have json text in unicode - then below example shows how to convert it to utf-8.

#include <string>
#include <locale>
#include <codecvt>
#include <iostream>
#include <iomanip>

int main()
{
   // On input in unicode
   std::wstring uStr = L"\u0105"; // polish a with ogonek

   // Convert uStr to utf-8
   std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> convert;
   std::string result = convert.to_bytes(uStr);

   // Output result,
   // U+0105 is converted to : U+00c4, U+0085,
   std::cout << "U+" << std::hex << std::setw(4) << std::setfill('0') << uStr[0] << std::endl;
   for ( char c : result ) {
    unsigned char uc = static_cast<unsigned char>(c);
    std::cout << "U+" << std::hex << std::setw(4) << std::setfill('0') <<  static_cast<int>(uc) << ", ";
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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