在 UE4 里面写 Json,然后保存到本地 txt 文件中。一共分为三步:
1.写 json 格式的数据
2.把这些 Json 格式的数据转换为字符串,保存到FString
变量中
3.把转换好的字符串保存到本地文件中
实现过程如下:
写 json 数据的函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
void MyJsonHandle::UpdateRecordData(FString culture,float musicVolume,float soundVolume,TArray<FString> *recordDataList) { TSharedPtr<FJsonObject> cultureObject = MakeShareable(new FJsonObject); cultureObject->SetStringField("Culture",culture); TSharedPtr<FJsonValueObject> cultureValue = MakeShareable(new FJsonValueObject(cultureObject)); TSharedPtr<FJsonObject> musicObject = MakeShareable(new FJsonObject); musicObject->SetNumField("MusicVolume",musicVolume); TSharedPtr<FJsonValueObject> musicValue = MakeShareable(new FJsonValueObject(musicObject)); TSharedPtr<FJsonObject> soundObject = MakeShareable(new FJsonObject); musicObject->SetNumField("MusicVolume",soundVolume); TSharedPtr<FJsonValueObject> musicValue = MakeShareable(new FJsonValueObject(soundObject)); TArray<SharedPtr<FJsonValue>> recordDataArray; for(int i = 0; i < recordDataList.Num(); ++i) { TSharedPtr<FJsonObject> recordItem = MakeShareable(new FJSonObject); recordItem->SetStringField(FString::FromInt(i), (*recordDataList)[i]); TSharedPtr<FJsonValueObject> recordDataValue = MakeShareable(new FJsonValueObject(recordItem)); recordDataArray.Add(recordDataValue); } TSharedPtr<FJsonObject> recordDataObject = MakeShareable(new FJsonObject); recordDataObject->SetArrayField("RecordData",recordDataArray); TSharedPtr<FJsonValueObject> recordDataValue = MakeShareable(new FJsonValueObject(recordDataObject)); TArray<TSharedPtr<FJsonValue>> baseDataArray; baseDataArray.Add(cultureValue); baseDataArray.Add(musicVolumeValue); baseDataArray.Add(soundVolumeValue); baseDataArray.Add(recordDataValue); TSharedPtr<FJsonObject> jsonObject = MakeShareable(new FJsonObject); jsonObject->SetArrayField("T",baseDataArray); FString jsonStr; GetFStringInJsonData(JsonObject,jsonStr); jsonStr.RemoveAt(0, 8); jsonStr.RemoveFromEnd(FString("}")); WriteFileWithJsonData(jsonStr,RelativePath,RecordDataFileName); }
|
1 2 3 4 5 6 7 8 9 10 11
|
void MyJsonHandle::GetFStringInJsonData(const TSharedPtr<FJsonObject>& jsonObj, FString& jsonStr) { if(jsonObj.IsValid() && jsonObject->Values.Num() > 0) { TSharedPtr<TJsonWriter<TCHAR>> jsonWrite = TJsonWriterFactory<TCHAR>::Creat(&jsonStr); FJsonSerializer::Serialize(jsonObj.ToSharedRef(), jsonWrite); } }
|
然后是写入本地操作
1 2 3 4 5 6 7 8 9 10 11 12
|
void MyJsonHandle::WriteFileWithJsonData(const FString& jsonStr, const FString& relaPath, const FString& fileName) { FString absoPath = FPaths::GameContentDir() + relaPath + fileName; if (FFileHelper::SaveStringToFile(jsonStr, *absoPath)) { }else { } }
|
总结:只有 FJsonObject 指针支持 Json 数据的创建,然后要转换为 FJsonValueObject 类型,最后就可以放到 FJsonValue 的数组中了。
最后将保存着所有数据的 FJsonValue 数组保存到 FJsonObject 类型的指针中,进行写入本地。