UE4 C++ serialization and deserialization
程序员文章站
2022-03-25 15:02:55
...
对以下 JSON 文件进行读写操作(序列化与反序列化)。
{ "nested": { "id": "i am nested id", "name": "this is the nested name" }, "foo": "i am test foo", "bar_arr": [ { "barfoo": "i am barfoo test" } ] }
定义好反序列化的文件对象结构:
USTRUCT() struct FNested { GENERATED_USTRUCT_BODY() UPROPERTY() FString id; UPROPERTY() FString name; }; USTRUCT() struct FBar { GENERATED_USTRUCT_BODY() UPROPERTY() FString barfoo; }; USTRUCT() struct FJsonData { GENERATED_USTRUCT_BODY() UPROPERTY() FNested nested; UPROPERTY() FString foo; UPROPERTY() TArray<FBar> bar_arr; //Transient 会阻止该属性被序列化 UPROPERTY(Transient) FString PropertyToIgnore; };
读写操作:
void UJsonSerializeComponent::Read() { FString FilePath = "F:\\svn-master\\thirdparty-master\\JsonSerializeSample\\Content\\test.json"; FString FileData = ""; if (!FPlatformFileManager::Get().GetPlatformFile().FileExists(*FilePath)) { UE_LOG(LogTemp, Warning, TEXT("DID NOT FIND FILE")); return; } FJsonData JsonData; FFileHelper::LoadFileToString(FileData, *FilePath); UE_LOG(LogTemp, Warning, TEXT("%s"), *FileData); if (FJsonObjectConverter::JsonObjectStringToUStruct(FileData, &JsonData, 0, 0)) { UE_LOG(LogTemp, Warning, TEXT("CONVERTED")); UE_LOG(LogTemp, Warning, TEXT("NestedName: %s "), *JsonData.nested.name); } } void UJsonSerializeComponent::Write() { FJsonData JsonData; JsonData.nested.id = "i am nested id2"; JsonData.nested.name = "this is the nested name2"; JsonData.foo = "i am test foo2"; FBar bar; bar.barfoo = "i am barfoo test2"; JsonData.bar_arr.Add(bar); FString JsonString; FJsonObjectConverter::UStructToJsonObjectString(JsonData, JsonString); //save to file FFileHelper::SaveStringToFile(JsonString, *FString("F:\\svn-master\\thirdparty-master\\JsonSerializeSample\\Content\\test.json")); }
记得要在 PublicDependencyModuleNames 中加入 "Json" 和 "JsonUtilities" 模块。