CHADALAK1
(CHADALAK1)
1
Hello Community!
I’ve been out of the loop with serializing and deserializing Json in C++. I know in C#, say example I have this
{
"Name" : "Dude",
"Age" : 12,
"Occupation" : "duder"
}
And for the serialized class class
[Serializable]
public class Person
{
public string Name;
public int Age;
public string Occupation;
}
I see everywhere online on how to retrieve the JSON text into a FJsonObject and FJsonReader, but I’m unsure on the steps to deserialize
C# (Unity) example
string jsonString = /* DO FILE IO STUFF TO GET JSON file as string */
Person person = JsonUtility.FromJson<Person>(jsonString);
How would one be able to deserialize a Person class from JSON in UE4 C++? Am I able to deserialize the values in a class/struct like this?
Zeblote
(Zeblote)
2
There is a tool to automatically serialize UStructs:
USTRUCT()
struct FPerson
{
GENERATED_BODY()
public:
UPROPERTY()
FString Name;
UPROPERTY()
FString Occupation;
UPROPERTY()
int32 Age;
};
To read:
FString Blah = ...;
FPerson Person;
if(!FJsonObjectConverter::JsonObjectStringToUStruct(Blah, &Person, 0, 0))
{
// error
}
To write:
FString Blah;
FPerson Person;
FJsonObjectConverter::UStructToJsonObjectString(Person, Blah);
9 Likes
CHADALAK1
(CHADALAK1)
3
Thank you soo much! Been looking around for this for quite some time. Muchly appreciate this!
1 Like
CHADALAK1
(CHADALAK1)
4
FString FilePath = "C:\\Users\\<YOUR_USER>\\Desktop\\Person.json";
FString FileData = "";
if (!FPlatformFileManager::Get().GetPlatformFile().FileExists(*FilePath))
{
UE_LOG(LogTemp, Warning, TEXT("DID NOT FIND FILE"));
return;
}
FPerson PersonJSON;
FFileHelper::LoadFileToString(FileData, *FilePath);
UE_LOG(LogTemp, Warning, TEXT("%s"), *FileData);
if (FJsonObjectConverter::JsonObjectStringToUStruct(FileData, &PersonJSON, 0, 0))
{
UE_LOG(LogTemp, Warning, TEXT("CONVERTED"));
UE_LOG(LogTemp, Warning, TEXT("Name: %s Age: %d Occupation: %s"), *PersonJSON.Name,
PersonJSON.Age, *PersonJSON.Occupation);
}
Just for persons needing a reference, this works out very well ^_^! able to get everything correct :D! Thank you again @**Zeblote !!! **
6 Likes
SharpC1
(SharpC1)
5
it works only for “Person” class, how can we use generic deserializing in c++?