java - UTF 8 Special Characters when converting JString to String in JNI -
i'm trying convert string jstring in jni, when string contains utf 8 special characters, doesn't seems saving in right way.
for example: “avda. espaᡬ 1” when should “avda. españa 1”.
this code:
jstr= env->newstringutf(str.c_str());
is there way convert jstring specifying utf 8 charset?
i copied these somewhere, added exception handling. work in production.
// jstring std::wstring std::wstring jstr2wsz(jnienv *env, jstring string) { std::wstring wstr; if (string == null) { return wstr; // empty string } try { const jchar *raw = env->getstringchars(string, null); if (raw != null) { jsize len = env->getstringlength(string); wstr.assign(raw, raw + len); env->releasestringchars(string, raw); } } catch (const std::exception ex) { std::cout << "exception in jstr2wsz translating string input " << string << std::endl; std::cout << "exception: " << ex.what() << std::endl; } return wstr; } // std::wstring jstring jstring wsz2jstr(jnienv *env, std::wstring cstr) { jstring result = nullptr; try { int len = cstr.size(); jchar* raw = new jchar[len]; memcpy(raw, cstr.c_str(), len * sizeof(wchar_t)); result = env->newstring(raw, len); delete[] raw; return result; } catch (const std::exception ex) { std::wcout << l"exception in wsz2jstr translating string input " << cstr << std::endl; std::cout << "exception: " << ex.what() << std::endl; } return result;
}