Hey guys,
I’ve been trying to wrap my head around this for a while and I can’t come up with a generic solution and my stubborn self isn’t satisfied with a hardcoded one.
Consider the following case: (abbreviated for clarity, hopefully)
// Stuff that doesn't change per item (type). doesn't need to be serialized
struct FItemBaseData : TableRowBase
{
FString Name;
Texture2d Icon
}
// custom data that accompanies a specific item
// could be any selection of data for different item types
class UStackableItemData : UItemData
{
int32 Quantity;
}
class UWeaponItemData : UItemData
{
int32 AmmoCount;
}
struct FInventoryItem
{
FItemBaseData BaseData;
UItemData ItemData;
}
class UInventoryComponent : UActorComponent
{
TArray<FInventoryItem> Items;
void RequestItemsFromDB();
}
The use-case is to de/serialize the UItemData to and from a database.
As I imagine it the the whole Items array would arrive in one payload. Without knowing better I’d assume a single data request is probably better to manage and more efficient in the long run.
Now, several problems arise:
- The FJsonObjectConverter can only convert UStructs to JSON payload and back again. It seems to do that neatly though. But UStructs, while you can derive, them you cannot down-cast them without losing the data from its children.
- That’s why I wanted to use UObjects instead because you can cast them as desired. But then you lose the ability to neatly serialize/de-serialize them into JSON
- Even if serialization works I didn’t find a way to create the right instance from a payload without manually checking what kind of payload it is (by passing meta data in the payload for instance). So I cannot generically create an object/struct instance from a payload.
E.g I’d like to avoid doing
UItemData* GetItemData(payload)
switch (payload.customdataclass)
{
case "Stackable":
UStackableItemData* data;
JsonToUObject(data, payload);
return data;
case "Weapon"
UWeaponItemData* data;
JsonToUObject(data, payload);
return data;
[...]
}
}
Is there a generic solution that I’m overlooking? Is there a different approach? Am I overthinking this? Am I really just too stubborn?
Thanks!