🌥制作記録🌥

創作に関することを書いていきます。だいたいゲーム系

【UE4】jsonを構造体で読み込む【4.22】

概要

jsonJsonObject::GetHogeField で取得するのではなく、構造体で取得したい。
その方法の📝

方法

1 . FJsonObjectConverter を使用してjsonテキストを構造体に変換したい。
なので JsonUtility Module<ProjectName>.Build.cs に追加する。

PublicDependencyModuleNames.Add("JsonUtilities");

docs.unrealengine.com

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);