環境
UE4.20.3
Visual Studio 2017 Community
Windows10
概要
とりあえずでこのリポジトリに突っ込んでるJsonLoad関数を文字に書き起こしただけの備忘録です。
github.com
UE4のゲーム実行時のオプションやプロパティ等を外部ファイルで編集したいとか
用途は何でもいいんですが、JsonFileを使いたい時があるのでLoaderのメモ書きを残しておきます。
JsonFileの読み込みについて
まずJsonLoaderを作成するにあたって、UE4で既存のModuleを利用するため参照の追加が必要です。
ProjectのBuild.csにJsonを追加します。
PublicDependencyModuleNames.AddRange( new string[] { "Core", "Json", // 追加 } );
続いて実際のLoad処理を書いていきますが、UE4側で既にJsonObject等の便利なクラスが用意されているので、そちらを使っていきます。
今回は雑把にBlueprintFunctionLibraryに書いていきます。
次に簡単なJsonを用意しました。
とりあえず一通り使うであろうbool, int, array, string, vector(float)が入っています。
// Example.json { "isFullScreen": false, "windowWidth": 1280, "exampleArray": [ { "exampleString": "Hello Json", "offset": { "x": 100.0, "y": 0.100, "z": 3.14 } } ] }
ここまでで一旦JsonObjectとjsonの作成ができました。
しかし、このままでは利用できないためJsonObjectから実際に値を取り出すコードを簡単に書いていきます。
#include "JsonFunctionLibrary.h" // pathは (ProjectDir)/Json/Example など bool AExampleActor::LoadJson(const FString& Path) { const auto JsonObject = UPSJsonFunctionLibrary::LoadJsonObject(JsonFile); if (JsonObject.IsValid() == false) { return false; } MaxFps = static_cast<float>(JsonObject->GetNumberField("MaxFps")); IsFullScreen = JsonObject->GetBoolField("isFullScreen"); WindowWidth = JsonObject->GetIntegerField("windowWidth"); const auto ArrayField = JsonObject->GetArrayField("exampleArray"); for (const auto Field : ArrayField) { const auto ObjectField = Field->AsObject(); ExampleString = ObjectField->GetStringField("exampleString"); auto const OffsetField = ObjectField->GetObjectField("offset"); Offset.X = static_cast<float>(OffsetField->GetNumberField("x")); Offset.Y = static_cast<float>(OffsetField->GetNumberField("y")); Offset.Z = static_cast<float>(OffsetField->GetNumberField("z")); } return true; }