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

上一篇:C++继承时子类使用父类构造函数时的注意


下一篇:速战速决 go - go 面向对象: 结构体(结构体标签,结构体和 json 互相转换)