其他分享
首页 > 其他分享> > UE4 读取Json

UE4 读取Json

作者:互联网

UE4 读取Json

添加模块

“Json”, “JsonUtilities”

PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore" , "Json", "JsonUtilities" });

新建蓝图函数库文件

#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "MainBlueprintFunctionLibrary.generated.h"

/**
 * 
 */
UCLASS()
class TESTPROJECT_API UMainBlueprintFunctionLibrary : public UBlueprintFunctionLibrary
{
	GENERATED_BODY()


	//读取字符串类型
	UFUNCTION(BlueprintCallable,Category="Json")
		static FString ReadJsonString(FString _path, FString _fieldName);

	//读取bool类型
	UFUNCTION(BlueprintCallable, Category = "Json")
		static bool ReadJsonBool(FString _path, FString _fieldName);

	//读取数字类型
	UFUNCTION(BlueprintCallable, Category = "Json")
		static float ReadJsonNum(FString _path, FString _fieldName);
};
#include "MainBlueprintFunctionLibrary.h"
#include "Serialization/JsonReader.h"
#include "Serialization/JsonSerializer.h"

FString UMainBlueprintFunctionLibrary::ReadJsonString(FString _path,FString _fieldName)
{

	FString returnString;
	FString path = FPaths::ProjectContentDir() + TEXT("/")+ _path;
	FString reslutString;
	if (FPaths::FileExists(path))
	{

		FFileHelper::LoadFileToString(reslutString, *path);
		TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject);
		TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(reslutString);
		if (FJsonSerializer::Deserialize(Reader, JsonObject))
		{
			returnString = JsonObject->GetStringField(_fieldName);
		}
	}

	return returnString;
}

bool UMainBlueprintFunctionLibrary::ReadJsonBool(FString _path, FString _fieldName)
{

	bool returnBool;
	FString path = FPaths::ProjectContentDir() + TEXT("/") + _path;
	FString reslutString;
	if (FPaths::FileExists(path))
	{

		FFileHelper::LoadFileToString(reslutString, *path);
		TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject);
		TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(reslutString);
		if (FJsonSerializer::Deserialize(Reader, JsonObject))
		{
			returnBool = JsonObject->GetBoolField(_fieldName);
		}
	}

	return returnBool;
}

float UMainBlueprintFunctionLibrary::ReadJsonNum(FString _path, FString _fieldName)
{

	float renturnNum;
	FString path = FPaths::ProjectContentDir() + TEXT("/") + _path;
	FString reslutString;
	if (FPaths::FileExists(path))
	{

		FFileHelper::LoadFileToString(reslutString, *path);
		TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject);
		TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(reslutString);
		if (FJsonSerializer::Deserialize(Reader, JsonObject))
		{
			renturnNum = JsonObject->GetNumberField(_fieldName);
		}
	}

	return renturnNum;
}

在这里插入图片描述

标签:读取,JsonObject,Json,fieldName,path,UE4,reslutString,FString
来源: https://blog.csdn.net/weixin_45959035/article/details/122822288