Unable to create or read the contents of a JSON object properly in Unreal Engine 5. I’m trying to send a JSON object to an API, but have determined the JSON object is either not being defined or the Serialize is not writing properly as the result is always: {
void UPlayerSessionManager::SendMetricRequest()
{
// TODO: Resolve Invalid JSON error
const FUniqueNetIdRepl LocalPlayerPlatformId = GetLocalPlayerPlatformId();
if (!LocalPlayerPlatformId.IsValid()) return;
FString UniqueNetIdString = LocalPlayerPlatformId.ToString();
FString Url = "https://api.graphjson.com/api/log";
// Setup Event data fields
TSharedPtr<FJsonObject> Event = MakeShareable(new FJsonObject);
Event->SetStringField(TEXT("userId"), TEXT("12345678"));
Event->SetStringField(TEXT("event"), TEXT("Session Created"));
//Setup GraphJSON mandatory fields
TSharedPtr<FJsonObject> Payload = MakeShareable(new FJsonObject);
FDateTime Now = FDateTime::UtcNow();
int64 UnixTimeStamp = Now.ToUnixTimestamp();
Payload->SetNumberField("timestamp", UnixTimeStamp);
Payload->SetStringField(FString("api_key"), FString("REDACTED"));
Payload->SetObjectField(FString("json"), Event);
Payload->SetStringField(FString("collection"), FString("NEW-GAME"));
FString JsonContent;
TSharedRef<TJsonWriter<>> Writer = TJsonWriterFactory<>::Create(&JsonContent);
if (FJsonSerializer::Serialize(Event.ToSharedRef(), Writer))
{
UE_LOG(LogTemp, Warning, TEXT("SendMetricsRequest: Json Write succeeded!"));
}
else
{
UE_LOG(LogTemp, Warning, TEXT("SendMetricsRequest: Json Write failed"))
}
// Create the Request to send to Data Collection
TSharedRef<IHttpRequest, ESPMode::ThreadSafe> Request = FHttpModule::Get().CreateRequest();
Request->SetVerb("POST");
Request->SetURL(Url);
Request->SetHeader("Content-Type", "application/json");
Request->SetContentAsString(JsonContent);
// DEBUG Json Structure
UE_LOG(LogTemp, Warning, TEXT("SendMetricsRequest: Json Content: %s"), *JsonContent);
Request->OnProcessRequestComplete().BindStatic(&OnMetricSendCompleted);
Request->ProcessRequest();
}
void UPlayerSessionManager::OnMetricSendCompleted(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bSuccessful)
{
if (bSuccessful && Response.IsValid())
{
FString ResponseContent = Response->GetContentAsString();
TSharedPtr<FJsonObject> ResponseJson;
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(ResponseContent);
if(FJsonSerializer::Deserialize(Reader, ResponseJson))
{
UE_LOG(LogTemp, Warning, TEXT("Received response: %s"), *ResponseContent);
}
}
else
{
FString ErrorMsg = "Error: " + Response->GetContentAsString();
UE_LOG(LogTemp, Warning, TEXT("SendMetricRequest: Failure"));
}
}