【UE4】jsonを構造体で読み込む【4.22】
概要
json、JsonObject::GetHogeField
で取得するのではなく、構造体で取得したい。
その方法の📝
方法
1 . FJsonObjectConverter
を使用してjsonテキストを構造体に変換したい。
なので JsonUtility Module
を<ProjectName>.Build.cs
に追加する。
PublicDependencyModuleNames.Add("JsonUtilities");
2 . パスと構造体を指定してよしなに読み込んでくれるコードを書く。
(UE_ERROR_LOGは独自に定義されたマクロです。エラーログを画面に表示するだけなので適当に置換してください。)
#pragma once #include "CoreMinimal.h" #include "Misc/Paths.h" #include "FileHelper.h" #include "JsonUtilities.h" #include "Kismet/BlueprintFunctionLibrary.h" #include "JsonFunctionLibrary.generated.h" /** * */ UCLASS() class HOGE_API UJsonFunctionLibrary : public UBlueprintFunctionLibrary { GENERATED_BODY() public: template<typename OutStructType> static bool CreateUStructFromJsonPath(FString fullPath, OutStructType* outStruct, int checkFlags, int skipFlags) { if (!FPaths::FileExists(fullPath)) { UE_ERROR_LOG(fullPath + "is not exist") return false; } FString jsonRawString; if (!FFileHelper::LoadFileToString(jsonRawString, *fullPath)) { UE_ERROR_LOG(fullPath + "failed reading file") return false; } if (!FJsonObjectConverter::JsonObjectStringToUStruct(jsonRawString, outStruct, checkFlags, skipFlags)) { UE_ERROR_LOG(fullPath + "failed deserialize") return false; } return true; } };
結果
実際に利用するときは以下の形で使えます
FString jsonFullPath = FPaths::ProjectDir().Append("testJsonFile").Append(TEXT(".json")); FSecretLoginConfiguration secretLoginConfiguration; UJsonFunctionLibrary::CreateUStructFromJsonPath<FSecretLoginConfiguration>(jsonFullPath, &secretLoginConfiguration, 0, 0);
C++でつくるUnreal Engineアプリ開発 for Windows & macOS 〜初歩からプラグイン開発まで〜
- 作者:鈴木 晃
- 発売日: 2018/02/25
- メディア: 単行本(ソフトカバー)