首页 > 代码库 > ue4 C++ json数据的读写

ue4 C++ json数据的读写

这是改变恢复机制的json文件的例子 

//写入

TSharedPtr<FJsonObject> RootObject = MakeShareable(newFJsonObject);
TArray< TSharedPtr<FJsonValue> > PackagesThatCanBeRestored;
TSharedPtr<FJsonObject> EntryObject = MakeShareable(new FJsonObject);
EntryObject->SetStringField(TEXT("PackagePathName"), TEXT("Temp/Untitled_1"));
EntryObject->SetStringField(TEXT("AutoSavePath"), TEXT("Temp/Untitled_1_Auto1.umap"));
TSharedPtr<FJsonValue> EntryValue = MakeShareable(new FJsonValueObject(EntryObject));
PackagesThatCanBeRestored.Add(EntryValue);
RootObject->SetBoolField(TEXT("RestoreEnabled"), true);
RootObject->SetArrayField(TEXT("Packages"), PackagesThatCanBeRestored);
constFStringFilename = FPaths::GameSavedDir() /TEXT("Autosaves") /TEXT("PackageRestoreData.json");
FArchive* constFileAr = IFileManager::Get().CreateFileWriter(*Filename, FILEWRITE_EvenIfReadOnly);
if (FileAr)
{
     TSharedRef<TJsonWriter< TCHAR, TPrettyJsonPrintPolicy<TCHAR> >> Writer = TJsonWriterFactory< TCHAR, TPrettyJsonPrintPolicy<TCHAR> >::Create(FileAr);  
     FJsonSerializer::Serialize(RootObject.ToSharedRef(), Writer);
     FileAr->Close();
}

// 读取本地json文件
       const FString Filename = FPaths::GameSavedDir() / TEXT("Autosaves") / TEXT("PackageRestoreData.json");
       FArchive* const FileAr = IFileManager::Get().CreateFileReader(*Filename);
       bool bJsonLoaded = false;
       TSharedPtr<FJsonObject> RootObject = MakeShareable(new FJsonObject);
       {
              TSharedRef<TJsonReader<TCHAR>> Reader = TJsonReaderFactory<TCHAR>::Create(FileAr);
              bJsonLoaded = FJsonSerializer::Deserialize(Reader, RootObject);
              FileAr->Close();
       }
       TMap<FString, FString> PackagesThatCanBeRestored;
       TArray< TSharedPtr<FJsonValue> > PackagesThatCanBeRestoredArray = RootObject->GetArrayField(TEXT("Packages"));
       int32 TiRen = RootObject->GetIntegerField(TEXT("TiRen"));
       for (auto It = PackagesThatCanBeRestoredArray.CreateConstIterator(); It; ++It)
       {
              TSharedPtr<FJsonObject> EntryObject = (*It)->AsObject();
              const FString PackagePathName = EntryObject->GetStringField(TEXT("PackagePathName"));
              const FString AutoSavePath = EntryObject->GetStringField(TEXT("AutoSavePath"));
              PackagesThatCanBeRestored.Add(PackagePathName, AutoSavePath);
       }
       for (auto It = PackagesThatCanBeRestored.CreateConstIterator(); It; ++It)
       {
              if (TiRen == 1)
              {
                     EditorStartupMap = FPaths::GameContentDir() / TEXT("Autosaves") / It->Value;
              }
              else
              {
                     EditorStartupMap = AutoSaveUtils::GetAutoSaveDir() / It->Value;
              }
       }

ue4 C++ json数据的读写