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

UE4 读取Json_第1张图片

你可能感兴趣的:(UE4,ue4)