1:添加JSON Modules
在Project.Build.cs文件中的PrivateDependencyModuleNames添加Json和JsonUtilities模块。
读取Json文件到字符串
private:
bool LoadStringFromFile(const FString& FileName, const FString& RelaPath, FString& ResultString);
bool SlAiJsonHandle::LoadStringFromFile(const FString& FileName, const FString& RelaPath, FString& ResultString)
{
if (!FileName.IsEmpty()) {
//获取绝对路径 (GameContent+相对路径+文件名)
FString AbsoPath = FPaths::GameContentDir() + RelaPath + FileName;
//判断文件是否存在文件
if (FPaths::FileExists(AbsoPath))
{
if (FFileHelper::LoadFileToString(ResultString, *AbsoPath))
{
return true;
}
else {
//加载不成功
SlAiHelper::Debug(FString("Load Error") + AbsoPath);
}
}
else {
//输出文件不存在
SlAiHelper::Debug(FString("File Not Exist") + AbsoPath);
}
}
return false;
}
解析存档方法 (读取到的json文件按内容,传入方法)
void RecordDataJsonRead(FString& Culture, float& MusicVolume, float& SoundVolume, TArray<FString>& RecordDataList);
void SlAiJsonHandle::RecordDataJsonRead(FString& Culture, float& MusicVolume, float& SoundVolume, TArray<FString>& RecordDataList)
{
//用于保存file读取的内容
FString JsonValue;
//载入
LoadStringFromFile(RecordDataFileName, RelativePath, JsonValue);
//保存解析出来的数据
TArray<TSharedPtr<FJsonValue>> JsonParsed;
//将JsonValue字符串中读取到JsonReader
TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(JsonValue);