Blog

Technical thoughts, troubleshooting, and development notes.

Blog/UE Development

Unreal DataTable and JSON: validate before replacing

JSON files can become DataTable rows, but clearing the table before parsing can destroy old data on a later failure. This workflow targets a UE5 C++ e

Back
This page's table of contents

Importing and Exporting DataTables with Json

Importing a Json Folder into a DataTable

	DataTable->EmptyTable();
    TArray<FString> JsonFiles;
    IFileManager::Get().FindFilesRecursive(JsonFiles, *JsonFolderPath, TEXT("*.json"), true, false, true);
    for(const auto JsonFilePath : JsonFiles)
    {
        FString JsonFileString;
        FFileHelper::LoadFileToString(JsonFileString, *JsonFilePath);
        const TSharedRef<TJsonReader<>> JsonReader = TJsonReaderFactory<>::Create(JsonFileString);
        TSharedPtr<FJsonObject> JsonObject;
        FJsonSerializer::Deserialize(JsonReader, JsonObject);
        if(JsonObject.IsValid() == false)
        {
            UE_LOG(DataTableDynamicSync, Error, TEXT("Failed to read file %s, please check if the Json object is correct"), *JsonFilePath);
            continue;	
        }
        void* RowData = FMemory::Malloc(DataTable->GetRowStruct()->GetStructureSize());
        FJsonObjectConverter::JsonObjectToUStruct(JsonObject.ToSharedRef(), DataTable->GetRowStruct(), RowData);	
        DataTable->AddRow(FName(JsonFilePath.RightChop(JsonFolderPath.Len()).LeftChop(5)), *static_cast<FTableRowBase*>(RowData));
    }
#if WITH_EDITOR
    DataTable->Modify(true);
#endif
    return true;

This implementation completely avoids the editor and works normally in packaged builds

Exporting a DataTable to a Folder

IFileManager::Get().DeleteDirectory(*JsonFolderPath, true, true);
for(auto const& It : DataTable->GetRowMap())
{
    FString JsonFileString;
    FJsonObjectConverter::UStructToJsonObjectString(DataTable->GetRowStruct(), It.Value, JsonFileString);
    FFileHelper::SaveStringToFile(JsonFileString, *(JsonFolderPath + It.Key.ToString() + TEXT(".json")));	
}
return true

This likewise completely avoids the editor and works normally in packaged builds