I have a large number of properties that span 3 classes (1 parent 2 child) and these need to get saved to Json so i cant just lump them all in a struct and use struct2json… I tagged properties that need to be saved with (meta=Json) so that way i can just loop thru properties and look for “Json” in metadata.
The following code works but i feel like its really ugly with all the ifs. Is there a better way?
TSharedRef<FJsonObject> JsonObject = MakeShared<FJsonObject>();
static const FName JsonStr = TEXT("Json");
UClass* DefaultClass = AArkWelderNPC::StaticClass();
AArkWelderNPC* DefaultNPC = Cast<AArkWelderNPC>(DefaultClass->GetDefaultObject());
for (FProperty* Property = DefaultClass->PropertyLink; Property; Property = Property->PropertyLinkNext)
{
if (Property->HasMetaData(JsonStr))
{
//todo: is there a better way then all these ifs ???
const void* ValuePtr = Property->ContainerPtrToValuePtr<void>(DefaultNPC);
const FString& ValueType = Property->GetCPPType();
if (ValueType == TEXT("float"))
{
const float Value = FFloatProperty::GetPropertyValue(ValuePtr);
JsonObject->SetNumberField(Property->GetNameCPP(), Value);
}
else if (ValueType == TEXT("int32"))
{
const int32 Value = FIntProperty::GetPropertyValue(ValuePtr);
JsonObject->SetNumberField(Property->GetNameCPP(), Value);
}
else if (ValueType == TEXT("bool"))
{
const FBoolProperty* BoolProperty = static_cast<FBoolProperty*>(Property);
bool Value = BoolProperty->GetPropertyValue_InContainer(DefaultNPC);
JsonObject->SetBoolField(Property->GetNameCPP(), Value);
}
else if (ValueType == TEXT("FText"))
{
const FText Value = FTextProperty::GetPropertyValue(ValuePtr);
JsonObject->SetStringField(Property->GetNameCPP(), Value.ToString());
}
}
}