Предлагаю обновленную версию вашего кода, которая будет возвращать отдельные переменные в Blueprint вместо одной строки. Также провел рефакторинг для улучшения читаемости и надежности кода.
AsyncProfileRequests.h:
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintAsyncActionBase.h"
#include "HttpModule.h"
#include "Interfaces/IHttpRequest.h"
#include "Interfaces/IHttpResponse.h"
#include "AsyncProfileRequests.generated.h"
USTRUCT(BlueprintType)
struct FUserProfileData
{
GENERATED_BODY()
UPROPERTY(BlueprintReadOnly)
int32 Id;
UPROPERTY(BlueprintReadOnly)
FString Fullname;
UPROPERTY(BlueprintReadOnly)
FString Gender;
UPROPERTY(BlueprintReadOnly)
FString DateOfBirth;
UPROPERTY(BlueprintReadOnly)
FString PreferredLanguage;
UPROPERTY(BlueprintReadOnly)
FString Email;
UPROPERTY(BlueprintReadOnly)
FString Phone;
};
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnProfileRequestSuccessDetailed, const FUserProfileData&, ProfileData);
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FOnProfileRequestFailed);
UCLASS()
class ARSPHERE_API UAsyncProfileRequests : public UBlueprintAsyncActionBase
{
GENERATED_BODY()
public:
// Get User Profile (GET)
UPROPERTY(BlueprintAssignable)
FOnProfileRequestSuccessDetailed OnGetUserProfileSuccess;
UPROPERTY(BlueprintAssignable)
FOnProfileRequestFailed OnGetUserProfileFailed;
UFUNCTION(BlueprintCallable, meta = (BlueprintInternalUseOnly = "true"), Category = "Profile")
static UAsyncProfileRequests* GetUserProfile(const FString& ServerURL, const FString& AuthToken);
void ExecuteGetUserProfile(const FString& ServerURL, const FString& AuthToken);
// Post User Profile (POST)
UPROPERTY(BlueprintAssignable)
FOnProfileRequestSuccessDetailed OnPostUserProfileSuccess;
UPROPERTY(BlueprintAssignable)
FOnProfileRequestFailed OnPostUserProfileFailed;
UFUNCTION(BlueprintCallable, meta = (BlueprintInternalUseOnly = "true"), Category = "Profile")
static UAsyncProfileRequests* PostUserProfile(const FString& ServerURL, const FString& Fullname, const FString& Gender, const FString& DateOfBirth, const FString& PreferredLanguage, const FString& Email, const FString& Phone, const FString& AuthToken);
void ExecutePostUserProfile(const FString& ServerURL, const FString& Fullname, const FString& Gender, const FString& DateOfBirth, const FString& PreferredLanguage, const FString& Email, const FString& Phone, const FString& AuthToken);
// Put User Profile (PUT)
UPROPERTY(BlueprintAssignable)
FOnProfileRequestSuccessDetailed OnPutUserProfileSuccess;
UPROPERTY(BlueprintAssignable)
FOnProfileRequestFailed OnPutUserProfileFailed;
UFUNCTION(BlueprintCallable, meta = (BlueprintInternalUseOnly = "true"), Category = "Profile")
static UAsyncProfileRequests* PutUserProfile(const FString& ServerURL, const FString& Fullname, const FString& Gender, const FString& DateOfBirth, const FString& PreferredLanguage, const FString& Email, const FString& Phone, const FString& AuthToken);
void ExecutePutUserProfile(const FString& ServerURL, const FString& Fullname, const FString& Gender, const FString& DateOfBirth, const FString& PreferredLanguage, const FString& Email, const FString& Phone, const FString& AuthToken);
private:
void OnGetUserProfileResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);
void OnPostUserProfileResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);
void OnPutUserProfileResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);
FUserProfileData ParseUserProfileDataFromJson(TSharedPtr<FJsonObject> JsonResponse);
};
AsyncProfileRequests.cpp:
#include "AsyncProfileRequests.h"
#include "HttpModule.h"
#include "Interfaces/IHttpRequest.h"
#include "Interfaces/IHttpResponse.h"
#include "Json.h"
#include "JsonUtilities.h"
// Helper function to parse JSON response into FUserProfileData
FUserProfileData UAsyncProfileRequests::ParseUserProfileDataFromJson(TSharedPtr<FJsonObject> JsonResponse)
{
FUserProfileData ProfileData;
if (JsonResponse.IsValid())
{
if (!JsonResponse->TryGetNumberField("id", ProfileData.Id))
{
UE_LOG(LogTemp, Warning, TEXT("JSON response missing or invalid 'id' field."));
}
if (!JsonResponse->TryGetStringField("fullname", ProfileData.Fullname))
{
UE_LOG(LogTemp, Warning, TEXT("JSON response missing or invalid 'fullname' field."));
}
if (!JsonResponse->TryGetStringField("gender", ProfileData.Gender))
{
UE_LOG(LogTemp, Warning, TEXT("JSON response missing or invalid 'gender' field."));
}
if (!JsonResponse->TryGetStringField("dataOfBirth", ProfileData.DateOfBirth))
{
UE_LOG(LogTemp, Warning, TEXT("JSON response missing or invalid 'dataOfBirth' field."));
}
if (!JsonResponse->TryGetStringField("preferedLanguage", ProfileData.PreferredLanguage))
{
UE_LOG(LogTemp, Warning, TEXT("JSON response missing or invalid 'preferedLanguage' field."));
}
if (!JsonResponse->TryGetStringField("email", ProfileData.Email))
{
UE_LOG(LogTemp, Warning, TEXT("JSON response missing or invalid 'email' field."));
}
if (!JsonResponse->TryGetStringField("phone", ProfileData.Phone))
{
UE_LOG(LogTemp, Warning, TEXT("JSON response missing or invalid 'phone' field."));
}
}
return ProfileData;
}
// GetUserProfile
UAsyncProfileRequests* UAsyncProfileRequests::GetUserProfile(const FString& ServerURL, const FString& AuthToken)
{
UAsyncProfileRequests* Action = NewObject<UAsyncProfileRequests>();
Action->ExecuteGetUserProfile(ServerURL, AuthToken);
return Action;
}
void UAsyncProfileRequests::ExecuteGetUserProfile(const FString& ServerURL, const FString& AuthToken)
{
TSharedRef<IHttpRequest, ESPMode::ThreadSafe> Request = FHttpModule::Get().CreateRequest();
Request->OnProcessRequestComplete().BindUObject(this, &UAsyncProfileRequests::OnGetUserProfileResponseReceived);
Request->SetURL(ServerURL + "/profile");
Request->SetVerb("GET");
Request->SetHeader("Content-Type", "application/json");
Request->SetHeader("Authorization", "Bearer " + AuthToken);
Request->ProcessRequest();
}
void UAsyncProfileRequests::OnGetUserProfileResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
if (!bWasSuccessful || !Response.IsValid() || Response->GetResponseCode() != 200)
{
UE_LOG(LogTemp, Error, TEXT("Failed to get user profile. Status code: %d"), Response.IsValid() ? Response->GetResponseCode() : -1);
OnGetUserProfileFailed.Broadcast();
return;
}
TSharedPtr<FJsonObject> JsonResponse;
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
if (FJsonSerializer::Deserialize(Reader, JsonResponse) && JsonResponse.IsValid())
{
UE_LOG(LogTemp, Log, TEXT("Successfully retrieved user profile."));
FUserProfileData ProfileData = ParseUserProfileDataFromJson(JsonResponse);
OnGetUserProfileSuccess.Broadcast(ProfileData);
}
else
{
UE_LOG(LogTemp, Error, TEXT("Failed to parse user profile response."));
OnGetUserProfileFailed.Broadcast();
}
}
// PostUserProfile
UAsyncProfileRequests* UAsyncProfileRequests::PostUserProfile(const FString& ServerURL, const FString& Fullname, const FString& Gender, const FString& DateOfBirth, const FString& PreferredLanguage, const FString& Email, const FString& Phone, const FString& AuthToken)
{
UAsyncProfileRequests* Action = NewObject<UAsyncProfileRequests>();
Action->ExecutePostUserProfile(ServerURL, Fullname, Gender, DateOfBirth, PreferredLanguage, Email, Phone, AuthToken);
return Action;
}
void UAsyncProfileRequests::ExecutePostUserProfile(const FString& ServerURL, const FString& Fullname, const FString& Gender, const FString& DateOfBirth, const FString& PreferredLanguage, const FString& Email, const FString& Phone, const FString& AuthToken)
{
TSharedRef<IHttpRequest, ESPMode::ThreadSafe> Request = FHttpModule::Get().CreateRequest();
Request->OnProcessRequestComplete().BindUObject(this, &UAsyncProfileRequests::OnPostUserProfileResponseReceived);
Request->SetURL(ServerURL + "/profile");
Request->SetVerb("POST");
Request->SetHeader("Content-Type", "application/json");
Request->SetHeader("Authorization", "Bearer " + AuthToken);
TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject());
JsonObject->SetStringField("fullname", Fullname);
JsonObject->SetStringField("gender", Gender);
JsonObject->SetStringField("dataOfBirth", DateOfBirth);
JsonObject->SetStringField("preferedLanguage", PreferredLanguage);
JsonObject->SetStringField("email", Email);
JsonObject->SetStringField("phone", Phone);
FString RequestBody;
TSharedRef<TJsonWriter<>> Writer = TJsonWriterFactory<>::Create(&RequestBody);
FJsonSerializer::Serialize(JsonObject.ToSharedRef(), Writer);
Request->SetContentAsString(RequestBody);
Request->ProcessRequest();
}
void UAsyncProfileRequests::OnPostUserProfileResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
if (!bWasSuccessful || !Response.IsValid() || Response->GetResponseCode() != 200)
{
UE_LOG(LogTemp, Error, TEXT("Failed to post user profile. Status code: %d"), Response.IsValid() ? Response->GetResponseCode() : -1);
OnPostUserProfileFailed.Broadcast();
return;
}
TSharedPtr<FJsonObject> JsonResponse;
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
if (FJsonSerializer::Deserialize(Reader, JsonResponse) && JsonResponse.IsValid())
{
UE_LOG(LogTemp, Log, TEXT("Successfully posted user profile."));
FUserProfileData ProfileData = ParseUserProfileDataFromJson(JsonResponse);
OnPostUserProfileSuccess.Broadcast(ProfileData);
}
else
{
UE_LOG(LogTemp, Error, TEXT("Failed to parse post user profile response."));
OnPostUserProfileFailed.Broadcast();
}
}
// PutUserProfile
UAsyncProfileRequests* UAsyncProfileRequests::PutUserProfile(const FString& ServerURL, const FString& Fullname, const FString& Gender, const FString& DateOfBirth, const FString& PreferredLanguage, const FString& Email, const FString& Phone, const FString& AuthToken)
{
UAsyncProfileRequests* Action = NewObject<UAsyncProfileRequests>();
Action->ExecutePutUserProfile(ServerURL, Fullname, Gender, DateOfBirth, PreferredLanguage, Email, Phone, AuthToken);
return Action;
}
void UAsyncProfileRequests::ExecutePutUserProfile(const FString& ServerURL, const FString& Fullname, const FString& Gender, const FString& DateOfBirth, const FString& PreferredLanguage, const FString& Email, const FString& Phone, const FString& AuthToken)
{
TSharedRef<IHttpRequest, ESPMode::ThreadSafe> Request = FHttpModule::Get().CreateRequest();
Request->OnProcessRequestComplete().BindUObject(this, &UAsyncProfileRequests::OnPutUserProfileResponseReceived);
Request->SetURL(ServerURL + "/profile");
Request->SetVerb("PUT");
Request->SetHeader("Content-Type", "application/json");
Request->SetHeader("Authorization", "Bearer " + AuthToken);
TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject());
JsonObject->SetStringField("fullname", Fullname);
JsonObject->SetStringField("gender", Gender);
JsonObject->SetStringField("dataOfBirth", DateOfBirth);
JsonObject->SetStringField("preferedLanguage", PreferredLanguage);
JsonObject->SetStringField("email", Email);
JsonObject->SetStringField("phone", Phone);
FString RequestBody;
TSharedRef<TJsonWriter<>> Writer = TJsonWriterFactory<>::Create(&RequestBody);
FJsonSerializer::Serialize(JsonObject.ToSharedRef(), Writer);
Request->SetContentAsString(RequestBody);
Request->ProcessRequest();
}
void UAsyncProfileRequests::OnPutUserProfileResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
if (!bWasSuccessful || !Response.IsValid() || Response->GetResponseCode() != 200)
{
UE_LOG(LogTemp, Error, TEXT("Failed to update user profile. Status code: %d"), Response.IsValid() ? Response->GetResponseCode() : -1);
OnPutUserProfileFailed.Broadcast();
return;
}
TSharedPtr<FJsonObject> JsonResponse;
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
if (FJsonSerializer::Deserialize(Reader, JsonResponse) && JsonResponse.IsValid())
{
UE_LOG(LogTemp, Log, TEXT("Successfully updated user profile."));
FUserProfileData ProfileData = ParseUserProfileDataFromJson(JsonResponse);
OnPutUserProfileSuccess.Broadcast(ProfileData);
}
else
{
UE_LOG(LogTemp, Error, TEXT("Failed to parse PUT User Profile response."));
OnPutUserProfileFailed.Broadcast();
}
}
Объяснение изменений:
-
Создание структуры FUserProfileData:
- Добавлена
USTRUCT(BlueprintType) структура FUserProfileData, которая содержит все поля, возвращаемые сервером.
- Это позволяет удобно передавать все данные профиля в Blueprint в виде одной переменной.
-
Обновление делегатов:
- Изменены делегаты на
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnProfileRequestSuccessDetailed, const FUserProfileData&, ProfileData);
- Теперь они передают структурированный профиль вместо одной строки.
-
Парсинг JSON в структуру:
- Добавлена приватная функция
ParseUserProfileDataFromJson, которая принимает TSharedPtr<FJsonObject> и возвращает заполненную структуру FUserProfileData.
- Используются методы
TryGetStringField и TryGetNumberField для безопасного извлечения данных из JSON.
-
Обновление методов ответа:
- В методах
OnGetUserProfileResponseReceived, OnPostUserProfileResponseReceived и OnPutUserProfileResponseReceived теперь используется функция ParseUserProfileDataFromJson для получения данных профиля.
- Вместо передачи строки в
Broadcast, теперь передается заполненная структура ProfileData.
-
Рефакторинг и оптимизация:
- Убрано повторяющееся извлечение данных из JSON, что улучшает читаемость и поддерживаемость кода.
- Добавлены проверки
Response.IsValid() и корректная обработка случаев, когда ответ не валидный.
- Логи улучшены для более информативного вывода в случае ошибок.
Теперь в Blueprint вы сможете получить доступ ко всем отдельным полям данных профиля через возвращаемую структуру FUserProfileData.