UE4 C++ serialization and deserialization
作者:互联网
对以下 JSON 文件进行读写操作(序列化与反序列化)。
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"
- }
- ]
- }
定义好反序列化的文件对象结构:
Java代码
- 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;
- };
读写操作:
Java代码- 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" 模块。
标签:UPROPERTY,bar,deserialization,JsonData,nested,C++,UE4,USTRUCT,FString 来源: https://www.cnblogs.com/diruizhixia/p/15212127.html