I’m trying to create a keybindings system that will read and write a JSon file between instances of the game. I was previously trying to use XML but found that the XML Parser was incomplete and couldn’t get it to do what I needed. Now I’m having trouble with Json as well, but I’m hoping that someone will be willing to help me sort though my issues.
I haven’t found an equivalent of XMLs Root Node or parent/child node system, so I set up a very basic class to help me explore JSon and get a sense of how it works. Currently I am triggering a breakpoint in SharedPointer.h. I am new to shared pointers as well so I’m probably doing something wrong there.
My header:
class VIKINGSECOND_API JsonParser
{
protected:
private:
TSharedPtr<FJsonObject> ParsedObject;
FString FileName;
bool bIsLoaded;
public:
JsonParser();
JsonParser(FString fileName);
~JsonParser();
void Save(FString fileName);
void Save();
void LoadFromFile(FString fileName);
FORCEINLINE bool IsLoaded() { UE_LOG(LogTemp, Warning, TEXT("IsLoaded")) return bIsLoaded; };
FORCEINLINE TSharedPtr<FJsonObject> Process() { return ParsedObject; };
FORCEINLINE void SetFileName(FString filePath) { FileName = filePath; };
};
My source:
JsonParser::JsonParser()
{
ParsedObject = MakeShareable(new FJsonObject());
bIsLoaded = false;
FileName = "";
}
JsonParser::JsonParser(FString fileName)
{
JsonParser();
LoadFromFile(fileName);
}
JsonParser::~JsonParser()
{
if (FileName != "")
Save(FileName);
}
void JsonParser::Save(FString fileName)
{
// Convert save game json object to string
FString SaveGameStringData;
// Writer
TSharedRef< TJsonWriter<> > JsonWriter = TJsonWriterFactory<>::Create(&SaveGameStringData);
FJsonSerializer::Serialize(ParsedObject.ToSharedRef(), JsonWriter);
FFileHelper::SaveStringToFile(*SaveGameStringData, *fileName);
}
void JsonParser::Save()
{
Save(FileName);
}
void JsonParser::LoadFromFile(FString fileName)
{
FileName = fileName;
FString LoadGameStringData;
if (FPlatformFileManager::Get().GetPlatformFile().FileExists(*FileName))
{
UE_LOG(LogTemp, Warning, TEXT("JsonParser LoadFromFile going into it"))
FFileHelper::LoadFileToString(LoadGameStringData, *fileName);
TSharedRef< TJsonReader<> >Reader = TJsonReaderFactory<>::Create(LoadGameStringData);
bool success = FJsonSerializer::Deserialize(Reader, ParsedObject);
bIsLoaded = success;
}
}
My calling code (from baseCharacter)
if (!FPlatformFileManager::Get().GetPlatformFile().FileExists(*Path))
{
FFileHelper::SaveStringToFile(TEXT(""), *Path);
JsonParser Parser(Path);
if (Parser.IsLoaded())
{
FString Field = TEXT("TEST");
FString TestValue = TEXT("Hellooo");
FJsonValueString Value(TestValue);
TSharedPtr<FJsonValueString> ValueCheck = MakeShareable(new FJsonValueString(TestValue));
Parser.Process()->SetField(TEXT("Test"), ValueCheck);
Parser.Save();
}
}
Many thanks for any help you can provide.