Convert FString to std::string

I am trying to use a JSON library in my code. I am still grasping very basics as I am total rookie with C++. I have a trouble of converting FString to std::string. I did found this wiki page, but for some reason I am getting bunch of japanese(?) characters as the result.

I’ve made this function which is correctly recognized by the json library to do the conversion. However I am sensing there is something not quiet right about it.

void to_json(json& j, const FString& value) {
	j = TCHAR_TO_UTF8(*value);
}

Here is the GitHub issue where I have been discussing this. Any idea what might be wrong please?

Edit

Actually I tried this without interference of the JSON lib and it behaves same way.

FString test = TEXT("MyTest");
std::string test2 = std::string(TCHAR_TO_UTF8(*test));
UE_LOG(LogTemp, Warning, TEXT("JSON %s"), test2.c_str());

Would produce following log statement: LogTemp:Warning: JSON 祍敔瑳

1 Like

The problem with your second example is that TEXT("JSON %s") doesn’t expect what you fed it. Try giving it a pointer to an FString like this:

 FString test = "MyTest";
 std::string test2 = std::string(TCHAR_TO_UTF8(*test));
 UE_LOG(LogTemp, Warning, TEXT("JSON %s"), *FString(test2.c_str()));

Also, there is no need for the first TEXT() macro.

5 Likes

Thanks for your answer, although a little bit late as I’ve given up and bought JSON plugin for UE which works great. This might come in handy later perhaps.

This is nice… if you want to destroy any character different from a-z…
To preserve the characters to revert from string to fstring
----> FString(UTF8_TO_TCHAR(test2.c_str()))